@linjz/opencode-qqbot 0.3.12 → 0.3.13
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/bin/openqq-setup.mjs +50 -50
- package/bin/openqq.js +47 -47
- package/dist/opencode-qqbot-plugin.js +3 -3
- package/dist/openqq-bot.js +1033 -191
- package/package.json +2 -2
- package/src/_FOLDER.md +19 -19
- package/src/bridge.ts +135 -15
- package/src/commands.ts +554 -554
- package/src/config.ts +121 -121
- package/src/core/bot-launcher.ts +146 -146
- package/src/core/card-approval.ts +146 -146
- package/src/core/context-buffer.ts +78 -78
- package/src/core/delivery.ts +105 -13
- package/src/core/discovery.ts +151 -151
- package/src/core/error-rescue.ts +33 -33
- package/src/core/file-log.ts +45 -45
- package/src/core/form-bridge.ts +388 -72
- package/src/core/form-journal.ts +214 -0
- package/src/core/gateway-state.ts +68 -0
- package/src/core/inbound-dedupe.ts +43 -0
- package/src/core/inflight-journal.ts +148 -21
- package/src/core/instance-lock.ts +28 -1
- package/src/core/linkwatch.ts +195 -195
- package/src/core/message-queue.ts +11 -0
- package/src/core/mirror.ts +182 -182
- package/src/core/outbox.ts +522 -0
- package/src/core/permission.ts +301 -301
- package/src/core/reply-limiter.ts +106 -106
- package/src/core/send-media.ts +90 -90
- package/src/core/util.ts +8 -8
- package/src/index.ts +162 -162
- package/src/opencode/_FOLDER.md +11 -11
- package/src/opencode/client.ts +89 -8
- package/src/opencode/eventstream.ts +138 -138
- package/src/opencode/history.ts +143 -143
- package/src/opencode/mirror.ts +85 -85
- package/src/opencode/sessions.ts +158 -158
- package/src/plugin-entry.ts +112 -112
- package/src/qq/_FOLDER.md +13 -13
- package/src/qq/api.ts +539 -539
- package/src/qq/gateway.ts +69 -20
- package/src/qq/media.ts +219 -219
- package/src/qq/sender.ts +300 -300
- package/src/qq/types.ts +154 -154
- package/tsconfig.json +24 -24
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// @input: fs/path/os, ../opencode/client (FormInfo), ../qq/types (MessageContext)
|
|
2
|
+
// @output: FormJournalEntry, FormJournal, createFormJournal, defaultFormJournalPath
|
|
3
|
+
// @pos: core - 表单交互恢复台账(同步落盘、原子替换、跨进程短临界区锁)
|
|
4
|
+
//
|
|
5
|
+
// 只保存恢复所需数据:表单定义、最小路由 ctx、答案与回显文本。QQ 原事件、附件、
|
|
6
|
+
// 引用内容和被动回复 msgId 一律不落盘;恢复后的通知必须使用主动消息语义。
|
|
7
|
+
import {
|
|
8
|
+
closeSync,
|
|
9
|
+
existsSync,
|
|
10
|
+
mkdirSync,
|
|
11
|
+
openSync,
|
|
12
|
+
readFileSync,
|
|
13
|
+
renameSync,
|
|
14
|
+
statSync,
|
|
15
|
+
unlinkSync,
|
|
16
|
+
writeFileSync,
|
|
17
|
+
} from "fs"
|
|
18
|
+
import { dirname, join } from "path"
|
|
19
|
+
import { homedir } from "os"
|
|
20
|
+
import type { FormInfo } from "../opencode/client.js"
|
|
21
|
+
import type { MessageContext } from "../qq/types.js"
|
|
22
|
+
|
|
23
|
+
export type FormLifecycleState = "pending" | "clickReceived" | "submitting" | "replied" | "cancelled" | "expired"
|
|
24
|
+
|
|
25
|
+
export interface FormJournalEntry {
|
|
26
|
+
form: FormInfo
|
|
27
|
+
ctx: MessageContext
|
|
28
|
+
userId: string
|
|
29
|
+
createdAt: number
|
|
30
|
+
state: FormLifecycleState
|
|
31
|
+
answer?: Record<string, unknown>
|
|
32
|
+
display?: string
|
|
33
|
+
interactionId?: string
|
|
34
|
+
updatedAt: number
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface FormJournal {
|
|
38
|
+
load: () => FormJournalEntry[]
|
|
39
|
+
put: (entry: FormJournalEntry) => void
|
|
40
|
+
remove: (userId: string, formID?: string) => void
|
|
41
|
+
clear: () => void
|
|
42
|
+
readonly path: string
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
interface FormJournalFile {
|
|
46
|
+
version: 1
|
|
47
|
+
entries: FormJournalEntry[]
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const LOCK_STALE_MS = 30_000
|
|
51
|
+
const LOCK_WAIT_MS = 5_000
|
|
52
|
+
const sleepArray = new Int32Array(new SharedArrayBuffer(4))
|
|
53
|
+
const STATES = new Set<FormLifecycleState>(["pending", "clickReceived", "submitting", "replied", "cancelled", "expired"])
|
|
54
|
+
|
|
55
|
+
export function defaultFormJournalPath(): string {
|
|
56
|
+
return process.env.QQ_FORM_JOURNAL_FILE || join(homedir(), ".openqq", "forms.json")
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 只保留恢复路由;空 msgId 明确表达重启后使用主动消息,而非复用过期被动窗口。 */
|
|
60
|
+
export function minimalFormContext(ctx: MessageContext): MessageContext {
|
|
61
|
+
return {
|
|
62
|
+
type: ctx.type,
|
|
63
|
+
userId: ctx.userId,
|
|
64
|
+
...(ctx.type === "group" && ctx.groupId ? { groupId: ctx.groupId } : {}),
|
|
65
|
+
msgId: "",
|
|
66
|
+
content: "",
|
|
67
|
+
...(ctx.timestamp ? { timestamp: ctx.timestamp } : {}),
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function validForm(value: unknown): value is FormInfo {
|
|
72
|
+
if (!value || typeof value !== "object") return false
|
|
73
|
+
const form = value as Partial<FormInfo>
|
|
74
|
+
return typeof form.id === "string" && typeof form.sessionID === "string" && typeof form.title === "string" && Array.isArray(form.fields)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function normalizeEntry(value: unknown): FormJournalEntry | undefined {
|
|
78
|
+
if (!value || typeof value !== "object") return undefined
|
|
79
|
+
const entry = value as Partial<FormJournalEntry>
|
|
80
|
+
if (
|
|
81
|
+
!validForm(entry.form) ||
|
|
82
|
+
!entry.ctx ||
|
|
83
|
+
(entry.ctx.type !== "c2c" && entry.ctx.type !== "group") ||
|
|
84
|
+
typeof entry.userId !== "string" ||
|
|
85
|
+
!entry.userId ||
|
|
86
|
+
typeof entry.createdAt !== "number" ||
|
|
87
|
+
!Number.isFinite(entry.createdAt) ||
|
|
88
|
+
typeof entry.updatedAt !== "number" ||
|
|
89
|
+
!Number.isFinite(entry.updatedAt) ||
|
|
90
|
+
!entry.state ||
|
|
91
|
+
!STATES.has(entry.state)
|
|
92
|
+
) {
|
|
93
|
+
return undefined
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
form: entry.form,
|
|
97
|
+
ctx: minimalFormContext({ ...entry.ctx, userId: entry.userId }),
|
|
98
|
+
userId: entry.userId,
|
|
99
|
+
createdAt: entry.createdAt,
|
|
100
|
+
state: entry.state,
|
|
101
|
+
...(entry.answer && typeof entry.answer === "object" && !Array.isArray(entry.answer) ? { answer: entry.answer } : {}),
|
|
102
|
+
...(typeof entry.display === "string" ? { display: entry.display } : {}),
|
|
103
|
+
...(typeof entry.interactionId === "string" ? { interactionId: entry.interactionId } : {}),
|
|
104
|
+
updatedAt: entry.updatedAt,
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function snapshot(entry: FormJournalEntry): FormJournalEntry {
|
|
109
|
+
return {
|
|
110
|
+
form: entry.form,
|
|
111
|
+
ctx: minimalFormContext(entry.ctx),
|
|
112
|
+
userId: entry.userId,
|
|
113
|
+
createdAt: entry.createdAt,
|
|
114
|
+
state: entry.state,
|
|
115
|
+
...(entry.answer ? { answer: entry.answer } : {}),
|
|
116
|
+
...(entry.display !== undefined ? { display: entry.display } : {}),
|
|
117
|
+
...(entry.interactionId ? { interactionId: entry.interactionId } : {}),
|
|
118
|
+
updatedAt: entry.updatedAt,
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function createFormJournal(path: string = defaultFormJournalPath()): FormJournal {
|
|
123
|
+
function read(): FormJournalEntry[] {
|
|
124
|
+
try {
|
|
125
|
+
if (!existsSync(path)) return []
|
|
126
|
+
const raw = JSON.parse(readFileSync(path, "utf-8")) as FormJournalFile | FormJournalEntry[]
|
|
127
|
+
// 接受早期数组原型,写入时统一升级为带 version 的对象格式。
|
|
128
|
+
const values = Array.isArray(raw) ? raw : raw?.version === 1 && Array.isArray(raw.entries) ? raw.entries : []
|
|
129
|
+
const byUser = new Map<string, FormJournalEntry>()
|
|
130
|
+
for (const value of values) {
|
|
131
|
+
const entry = normalizeEntry(value)
|
|
132
|
+
if (!entry) continue
|
|
133
|
+
const previous = byUser.get(entry.userId)
|
|
134
|
+
if (!previous || previous.updatedAt <= entry.updatedAt) byUser.set(entry.userId, entry)
|
|
135
|
+
}
|
|
136
|
+
return [...byUser.values()].sort((a, b) => a.createdAt - b.createdAt)
|
|
137
|
+
} catch (error) {
|
|
138
|
+
// 损坏文件不阻塞 bot 启动;调用方仍可按服务端 reconcile 重建本地槽。
|
|
139
|
+
console.warn("[form-journal] 台账读取失败,按空台账处理:", error instanceof Error ? error.message : error)
|
|
140
|
+
return []
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function write(entries: FormJournalEntry[]): void {
|
|
145
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
146
|
+
const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
|
|
147
|
+
const payload: FormJournalFile = { version: 1, entries: entries.map(snapshot) }
|
|
148
|
+
try {
|
|
149
|
+
writeFileSync(tmp, JSON.stringify(payload, null, 2), { mode: 0o600 })
|
|
150
|
+
renameSync(tmp, path)
|
|
151
|
+
} catch (error) {
|
|
152
|
+
try { unlinkSync(tmp) } catch { /* 已 rename 或清理失败 */ }
|
|
153
|
+
throw error
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function withLock<T>(fn: () => T): T {
|
|
158
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
159
|
+
const lockPath = `${path}.lock`
|
|
160
|
+
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`
|
|
161
|
+
const deadline = Date.now() + LOCK_WAIT_MS
|
|
162
|
+
for (;;) {
|
|
163
|
+
try {
|
|
164
|
+
const fd = openSync(lockPath, "wx", 0o600)
|
|
165
|
+
try { writeFileSync(fd, token) } finally { closeSync(fd) }
|
|
166
|
+
break
|
|
167
|
+
} catch (error) {
|
|
168
|
+
try {
|
|
169
|
+
if (Date.now() - statSync(lockPath).mtimeMs > LOCK_STALE_MS) unlinkSync(lockPath)
|
|
170
|
+
} catch { /* 锁不存在或另一进程正在接管 */ }
|
|
171
|
+
if (Date.now() >= deadline) {
|
|
172
|
+
throw new Error(`表单台账锁等待超时: ${error instanceof Error ? error.message : error}`)
|
|
173
|
+
}
|
|
174
|
+
Atomics.wait(sleepArray, 0, 0, 10)
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
try {
|
|
178
|
+
return fn()
|
|
179
|
+
} finally {
|
|
180
|
+
try {
|
|
181
|
+
if (readFileSync(lockPath, "utf-8") === token) unlinkSync(lockPath)
|
|
182
|
+
} catch { /* 已被 stale 清理 */ }
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function mutate(fn: (entries: FormJournalEntry[]) => void): void {
|
|
187
|
+
withLock(() => {
|
|
188
|
+
const entries = read()
|
|
189
|
+
fn(entries)
|
|
190
|
+
write(entries)
|
|
191
|
+
})
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
return {
|
|
195
|
+
path,
|
|
196
|
+
load: read,
|
|
197
|
+
put(entry) {
|
|
198
|
+
mutate((entries) => {
|
|
199
|
+
const index = entries.findIndex((item) => item.userId === entry.userId)
|
|
200
|
+
if (index >= 0) entries[index] = snapshot(entry)
|
|
201
|
+
else entries.push(snapshot(entry))
|
|
202
|
+
})
|
|
203
|
+
},
|
|
204
|
+
remove(userId, formID) {
|
|
205
|
+
mutate((entries) => {
|
|
206
|
+
const index = entries.findIndex((item) => item.userId === userId && (!formID || item.form.id === formID))
|
|
207
|
+
if (index >= 0) entries.splice(index, 1)
|
|
208
|
+
})
|
|
209
|
+
},
|
|
210
|
+
clear() {
|
|
211
|
+
withLock(() => write([]))
|
|
212
|
+
},
|
|
213
|
+
}
|
|
214
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// @input: fs/path/os(落盘)、env(窗口可调)
|
|
2
|
+
// @output: loadGatewayState, saveGatewayState, clearGatewayState, GATEWAY_STATE_FILE
|
|
3
|
+
// @pos: core - QQ 网关 session/seq 持久化(修复②:重启不再 IDENTIFY 失忆重刷 backlog)
|
|
4
|
+
//
|
|
5
|
+
// 背景(2026-11-03 定案):gateway 的 session/seq 原先只在内存,进程重启即失忆 →
|
|
6
|
+
// 走 IDENTIFY → 服务端断线窗口事件重放 + 启动对账把旧账再跑一遍 = 放大器A
|
|
7
|
+
// (openqq423/429 ghost 铁证)。持久化后重启优先 RESUME,失败由服务端
|
|
8
|
+
// op9 InvalidSession 回退 IDENTIFY(gateway 已有该处理路径,无死循环)。
|
|
9
|
+
// 风控:文件只存 session_id/seq/时间戳,无凭据;损坏/超龄一律作废不阻塞启动;
|
|
10
|
+
// 保存走临时文件原子 rename,与台账同风格。
|
|
11
|
+
import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, unlinkSync } from "fs"
|
|
12
|
+
import { join } from "path"
|
|
13
|
+
import { homedir } from "os"
|
|
14
|
+
|
|
15
|
+
export interface GatewayPersistState {
|
|
16
|
+
session_id: string
|
|
17
|
+
seq: number
|
|
18
|
+
savedAt: number
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const GATEWAY_STATE_FILE = join(homedir(), ".openqq", "gateway-state.json")
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* RESUME 尝试窗口:QQ 网关断线会话 TTL 观测约 1h(427 每小时 RESUMED 实证)。
|
|
25
|
+
* 这里放宽到 6h 只是「值得试」的上限——超龄直接 IDENTIFY;RESUME 失败有 op9 回退,
|
|
26
|
+
* 不会死循环。env QQ_GATEWAY_STATE_MAX_HOURS 可调。
|
|
27
|
+
*/
|
|
28
|
+
export function gatewayStateMaxAgeMs(): number {
|
|
29
|
+
const h = Number(process.env.QQ_GATEWAY_STATE_MAX_HOURS ?? "6")
|
|
30
|
+
return Number.isFinite(h) && h > 0 ? Math.floor(h * 3600_000) : 6 * 3600_000
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 读取持久化网关状态;缺损/超龄返回 null(调用方走 IDENTIFY) */
|
|
34
|
+
export function loadGatewayState(file: string = GATEWAY_STATE_FILE, now: number = Date.now()): GatewayPersistState | null {
|
|
35
|
+
try {
|
|
36
|
+
if (!existsSync(file)) return null
|
|
37
|
+
const raw = JSON.parse(readFileSync(file, "utf-8")) as Partial<GatewayPersistState>
|
|
38
|
+
if (!raw || typeof raw.session_id !== "string" || !raw.session_id) return null
|
|
39
|
+
if (typeof raw.seq !== "number" || raw.seq < 0) return null
|
|
40
|
+
if (typeof raw.savedAt !== "number" || !Number.isFinite(raw.savedAt)) return null
|
|
41
|
+
if (now - raw.savedAt > gatewayStateMaxAgeMs()) return null // 超龄作废
|
|
42
|
+
return { session_id: raw.session_id, seq: raw.seq, savedAt: raw.savedAt }
|
|
43
|
+
} catch {
|
|
44
|
+
return null // 损坏即无状态,不阻塞启动
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 原子落盘网关状态(每载荷推进调用;小文件低频,不做节流) */
|
|
49
|
+
export function saveGatewayState(sessionId: string, seq: number, file: string = GATEWAY_STATE_FILE): void {
|
|
50
|
+
try {
|
|
51
|
+
mkdirSync(join(file, ".."), { recursive: true })
|
|
52
|
+
const tmp = `${file}.${process.pid}.tmp`
|
|
53
|
+
writeFileSync(tmp, JSON.stringify({ session_id: sessionId, seq, savedAt: Date.now() }))
|
|
54
|
+
renameSync(tmp, file)
|
|
55
|
+
} catch (error) {
|
|
56
|
+
// 持久化失败不致命:本连接周期内仍走内存态,重叠留观
|
|
57
|
+
console.warn("[gateway-state] 落盘失败:", error instanceof Error ? error.message : error)
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 清账:仅在服务端明确作废会话(op9 不可恢复/Resume 失效码)时调用 */
|
|
62
|
+
export function clearGatewayState(file: string = GATEWAY_STATE_FILE): void {
|
|
63
|
+
try {
|
|
64
|
+
unlinkSync(file)
|
|
65
|
+
} catch {
|
|
66
|
+
/* 不存在/已清理 */
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// @input: node:crypto(指纹哈希)
|
|
2
|
+
// @output: messageFingerprint, admissionDecision, AdmissionKind, AdmissionInput
|
|
3
|
+
// @pos: core - 入站受理去重判定(K1 同 msgId 占位 + K2 在途内容指纹)
|
|
4
|
+
//
|
|
5
|
+
// 背景(2026-11-03 根因定案):重复回复主链=多 believer 并存、同 msgId 并发受理;
|
|
6
|
+
// 且不同 msgId 的相同意图(同文连发不同 msgId)也会重复执行。修复语义经用户拍板
|
|
7
|
+
// (2026-11-02):去重只管「并发在途」窗口——已完成消息的重投按重发处理,不做
|
|
8
|
+
// 长窗已答拦截。在途判定数据源=在途台账(inflight-journal,跨进程原子),本模块
|
|
9
|
+
// 只做纯判定与指纹,不持有状态(台账即状态,进程不私有)。
|
|
10
|
+
//
|
|
11
|
+
// K1:同 msgId 在途(含其他进程认领)→ 拒绝;K2:同用户同内容指纹在途 → 拒绝。
|
|
12
|
+
// 两者窗口都=in-flight;settle 即释放,重投/重发重新放行。
|
|
13
|
+
// 回执纪律:duplicate-msgid 静默(另一个 believer 会给答案,本侧任何回复都是气泡);
|
|
14
|
+
// duplicate-intent 给「正在处理中」短提示(首投方不会发,不构成重复)。
|
|
15
|
+
import { createHash } from "crypto"
|
|
16
|
+
|
|
17
|
+
export type AdmissionKind = "ok" | "duplicate-msgid" | "duplicate-intent"
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* K2 内容指纹:同用户 + 归一化意图(文本/引用/附件签名)相同 → 同一意图。
|
|
21
|
+
* 核入 userId 防跨用户误拦;intentKey 复用 message-queue 的意图键(busy 分支同源)。
|
|
22
|
+
*/
|
|
23
|
+
export function messageFingerprint(userId: string, intentKey: string): string {
|
|
24
|
+
return createHash("sha256").update(`${userId}\u0000${intentKey}`).digest("hex").slice(0, 32)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface AdmissionInput {
|
|
28
|
+
/** K1:台账里已有同 msgId 在途(任何进程认领的都算) */
|
|
29
|
+
hasSameMsgIdInflight: boolean
|
|
30
|
+
/** 本条指纹;空串跳过 K2(重派回合/无文本消息不参与指纹拦) */
|
|
31
|
+
fingerprint: string
|
|
32
|
+
/** K2:台账里全部在途记录的指纹 */
|
|
33
|
+
inflightFingerprints: readonly string[]
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 受理判定(纯函数):只看并发在途;settled/被修剪的旧账不拦 */
|
|
37
|
+
export function admissionDecision(input: AdmissionInput): AdmissionKind {
|
|
38
|
+
if (input.hasSameMsgIdInflight) return "duplicate-msgid"
|
|
39
|
+
if (input.fingerprint && input.inflightFingerprints.includes(input.fingerprint)) {
|
|
40
|
+
return "duplicate-intent"
|
|
41
|
+
}
|
|
42
|
+
return "ok"
|
|
43
|
+
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// @input: fs/path/os(台账落盘)
|
|
2
2
|
// @output: claimInflight, recordInflight, settleInflight, pendingInflight, classifyInflight(纯函数供测试),
|
|
3
|
-
//
|
|
3
|
+
// pruneInflightEntries(保留策略纯函数), newInflightAttemptId,
|
|
4
|
+
// resetInflightJournal(测试用),
|
|
5
|
+
// INFLIGHT_MAX_AGE_MS, SETTLED_RETENTION_MS, SETTLED_RETENTION_LIMIT, redispatchMaxAgeMs
|
|
4
6
|
// @pos: core - 在途台账(重启换代丢消息修复:QQ 消息派发落账、答复送达销账、启动对账)
|
|
5
7
|
//
|
|
6
8
|
// 事故背景(2026-10-30,用户实证):bot 重启/网关静默死亡窗口内到达的 QQ 消息
|
|
@@ -9,6 +11,7 @@
|
|
|
9
11
|
import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, openSync, closeSync, unlinkSync, statSync } from "fs"
|
|
10
12
|
import { join } from "path"
|
|
11
13
|
import { homedir } from "os"
|
|
14
|
+
import { admissionDecision } from "./inbound-dedupe.js"
|
|
12
15
|
|
|
13
16
|
export interface InflightEntry {
|
|
14
17
|
/** 跟踪键:真实 QQ msgId;重派回合为合成键 redispatch-<sessionId>-<ts> */
|
|
@@ -19,11 +22,47 @@ export interface InflightEntry {
|
|
|
19
22
|
text: string
|
|
20
23
|
at: number
|
|
21
24
|
state: "inflight" | "settled"
|
|
25
|
+
/**
|
|
26
|
+
* 投递代次:settled 允许重新认领后,旧回合迟到的销账/落账回调不得
|
|
27
|
+
* 作用到新代次。settle 带 attemptId 时必须 msgId+attemptId 双匹配。
|
|
28
|
+
*/
|
|
29
|
+
attemptId?: string
|
|
30
|
+
/** K2 内容指纹(messageFingerprint;受理时原子写入,随 settle 释放) */
|
|
31
|
+
fingerprint?: string
|
|
32
|
+
/** 本回合的 prompt 用户消息 id(修复⑧直答归属的回合边界锚点) */
|
|
33
|
+
promptId?: string
|
|
22
34
|
}
|
|
23
35
|
|
|
24
|
-
|
|
25
|
-
|
|
36
|
+
/** 生成新的投递代次 ID(bridge 显式新回合/显式重投时调用) */
|
|
37
|
+
export function newInflightAttemptId(): string {
|
|
38
|
+
return `att-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// 启动对账年龄上限:超 24h 的在途账仍保留在文件中,但恢复时不再追溯(由恢复流程销账)。
|
|
26
42
|
export const INFLIGHT_MAX_AGE_MS = 24 * 60 * 60 * 1000
|
|
43
|
+
// settled 记录只保留 24h 内、按 at 最新的 20 条;inflight 不受年龄或数量限制。
|
|
44
|
+
export const SETTLED_RETENTION_MS = INFLIGHT_MAX_AGE_MS
|
|
45
|
+
export const SETTLED_RETENTION_LIMIT = 20
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 台账保留策略(纯函数):保留全部 inflight;settled 先按 24h 过滤,再按 at 取最新 20 条。
|
|
49
|
+
* 输出按 at 升序;at 相同时保持输入相对顺序。数量上限并列时保留输入中靠后的记录。
|
|
50
|
+
*/
|
|
51
|
+
export function pruneInflightEntries(entries: InflightEntry[], now = Date.now()): InflightEntry[] {
|
|
52
|
+
const indexed = entries.map((entry, index) => ({ entry, index }))
|
|
53
|
+
const retainedSettled = new Set(
|
|
54
|
+
indexed
|
|
55
|
+
.filter(({ entry }) => entry.state === "settled" && now - entry.at <= SETTLED_RETENTION_MS)
|
|
56
|
+
.sort((a, b) => b.entry.at - a.entry.at || b.index - a.index)
|
|
57
|
+
.slice(0, SETTLED_RETENTION_LIMIT)
|
|
58
|
+
.map(({ index }) => index),
|
|
59
|
+
)
|
|
60
|
+
return indexed
|
|
61
|
+
.filter(({ entry, index }) => entry.state === "inflight" || retainedSettled.has(index))
|
|
62
|
+
.sort((a, b) => a.entry.at - b.entry.at || a.index - b.index)
|
|
63
|
+
.map(({ entry }) => entry)
|
|
64
|
+
}
|
|
65
|
+
|
|
27
66
|
// 丢失消息自动重派窗口(2026-10-30 用户拍板:默认 2 小时,env QQ_REDISPATCH_MAX_AGE_MS
|
|
28
67
|
// 可调;0=关闭自动重派一律通知)。窗口内视为"意图仍然新鲜"自动重派;超期只通知请用户
|
|
29
68
|
// 重发——防"陈旧意图"在重启时被意外执行。
|
|
@@ -48,16 +87,17 @@ function load(): InflightEntry[] {
|
|
|
48
87
|
entries = [] // 损坏即空,不阻塞启动
|
|
49
88
|
}
|
|
50
89
|
// 读取始终走磁盘:多个 bot 执行体可能共享台账,进程内 cache 会看不到彼此的认领。
|
|
51
|
-
return entries
|
|
90
|
+
return pruneInflightEntries(entries)
|
|
52
91
|
}
|
|
53
92
|
|
|
54
93
|
function save(entries: InflightEntry[]): void {
|
|
55
94
|
const path = journalPath()
|
|
56
95
|
mkdirSync(join(path, ".."), { recursive: true })
|
|
96
|
+
const retained = pruneInflightEntries(entries)
|
|
57
97
|
// 临时文件带进程与随机后缀:并发执行体不会互相覆盖对方的 tmp。
|
|
58
98
|
const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
|
|
59
99
|
try {
|
|
60
|
-
writeFileSync(tmp, JSON.stringify(
|
|
100
|
+
writeFileSync(tmp, JSON.stringify(retained, null, 2), { mode: 0o600 }) // 台账含用户消息,POSIX 仅本人可读
|
|
61
101
|
renameSync(tmp, path)
|
|
62
102
|
} catch (error) {
|
|
63
103
|
try { unlinkSync(tmp) } catch { /* 已改名或清理失败 */ }
|
|
@@ -116,35 +156,85 @@ function mutate<T>(fn: (entries: InflightEntry[]) => T): T {
|
|
|
116
156
|
})
|
|
117
157
|
}
|
|
118
158
|
|
|
159
|
+
/** 受理结果:K1/K2 细分给调用方决定回执纪律(msgid 静默 / intent 给短提示) */
|
|
160
|
+
export type ClaimOutcome = "ok" | "duplicate-msgid" | "duplicate-intent"
|
|
161
|
+
|
|
119
162
|
/**
|
|
120
|
-
* AI
|
|
121
|
-
*
|
|
163
|
+
* AI 派发前原子认领(修复①):withinJournalLock 单临界区内同时做 K1+K2——
|
|
164
|
+
* - K1:同 msgId 已在途(任何进程认领的都算)→ duplicate-msgid;
|
|
165
|
+
* - K2:同用户同内容指纹在同窗在途(不同 msgId 的相同意图)→ duplicate-intent;
|
|
166
|
+
* 判定与写入原子,杜绝「两进程都看到无占位→双双放行」的竞态。
|
|
167
|
+
* 窗口=in-flight:settle 即释放指纹与 msgId 占位,重投/重发重新放行(用户拍板)。
|
|
168
|
+
* 已销账记录允许重新投递,并原位复用、更新为传入的新在途回合(代次 = 传入
|
|
169
|
+
* attemptId;未传则生成新代次);不另建去重文件。
|
|
170
|
+
* 被 24h/20 条保留策略裁掉的旧 msgId 也可正常认领。
|
|
122
171
|
*/
|
|
123
|
-
export function
|
|
172
|
+
export function claimInflightDetailed(entry: Omit<InflightEntry, "state">, opts?: { fingerprint?: string }): ClaimOutcome {
|
|
124
173
|
return mutate((entries) => {
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
174
|
+
const fingerprint = opts?.fingerprint ?? entry.fingerprint ?? ""
|
|
175
|
+
const decision = admissionDecision({
|
|
176
|
+
hasSameMsgIdInflight: entries.some((e) => e.msgId === entry.msgId && e.state === "inflight"),
|
|
177
|
+
fingerprint,
|
|
178
|
+
inflightFingerprints: entries
|
|
179
|
+
.filter((e) => e.state === "inflight" && e.fingerprint)
|
|
180
|
+
.map((e) => e.fingerprint as string),
|
|
181
|
+
})
|
|
182
|
+
if (decision !== "ok") return decision
|
|
183
|
+
const attempt = entry.attemptId ?? newInflightAttemptId()
|
|
184
|
+
const existing = entries.find((e) => e.msgId === entry.msgId)
|
|
185
|
+
if (existing) {
|
|
186
|
+
Object.assign(existing, entry, { fingerprint, attemptId: attempt, state: "inflight" as const })
|
|
187
|
+
} else {
|
|
188
|
+
entries.push({ ...entry, fingerprint, attemptId: attempt, state: "inflight" as const })
|
|
189
|
+
}
|
|
190
|
+
return "ok"
|
|
128
191
|
})
|
|
129
192
|
}
|
|
130
193
|
|
|
131
|
-
/**
|
|
194
|
+
/** 兼容旧布尔签名的认领(测试与既有调用方) */
|
|
195
|
+
export function claimInflight(entry: Omit<InflightEntry, "state">): boolean {
|
|
196
|
+
return claimInflightDetailed(entry) === "ok"
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* 派发落账:
|
|
201
|
+
* - 同 msgId + 同 attemptId 且在途:幂等,仅允许后补 sessionId;
|
|
202
|
+
* - attemptId 不匹配:迟到回调,不得覆盖新回合;
|
|
203
|
+
* - 已 settled:显式重投重新激活(换新代次与新的 at/user/session/text);
|
|
204
|
+
* - 无记录:新增在途。
|
|
205
|
+
*/
|
|
132
206
|
export function recordInflight(entry: Omit<InflightEntry, "state">): void {
|
|
133
207
|
mutate((entries) => {
|
|
134
208
|
const existing = entries.find((e) => e.msgId === entry.msgId)
|
|
135
209
|
if (existing) {
|
|
136
|
-
if (
|
|
210
|
+
if (existing.state === "inflight") {
|
|
211
|
+
if (entry.attemptId && existing.attemptId && entry.attemptId !== existing.attemptId) return
|
|
212
|
+
if (!existing.sessionId && entry.sessionId) existing.sessionId = entry.sessionId
|
|
213
|
+
if (!existing.promptId && entry.promptId) existing.promptId = entry.promptId
|
|
214
|
+
return
|
|
215
|
+
}
|
|
216
|
+
// settled:视为显式重投,重新激活为新在途回合
|
|
217
|
+
const attempt = entry.attemptId ?? newInflightAttemptId()
|
|
218
|
+
Object.assign(existing, entry, { attemptId: attempt, state: "inflight" as const })
|
|
137
219
|
return
|
|
138
220
|
}
|
|
139
|
-
entries.push({ ...entry, state: "inflight" })
|
|
221
|
+
entries.push({ ...entry, attemptId: entry.attemptId ?? newInflightAttemptId(), state: "inflight" as const })
|
|
140
222
|
})
|
|
141
223
|
}
|
|
142
224
|
|
|
143
|
-
/**
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
225
|
+
/**
|
|
226
|
+
* 销账:答复已送达(或已转入有接管的后台等待/已给用户终态反馈)。
|
|
227
|
+
* 传入 attemptId 时必须 msgId + attemptId 双匹配才销账——settled 重新认领后,
|
|
228
|
+
* 旧代次的迟到 settle 不得把新在途回合误销。返回是否实际销账。
|
|
229
|
+
*/
|
|
230
|
+
export function settleInflight(msgId: string, attemptId?: string): boolean {
|
|
231
|
+
return mutate((entries) => {
|
|
232
|
+
const entry = entries.find(
|
|
233
|
+
(e) => e.msgId === msgId && e.state === "inflight" && (!attemptId || !e.attemptId || e.attemptId === attemptId),
|
|
234
|
+
)
|
|
235
|
+
if (!entry) return false
|
|
236
|
+
entry.state = "settled"
|
|
237
|
+
return true
|
|
148
238
|
})
|
|
149
239
|
}
|
|
150
240
|
|
|
@@ -153,6 +243,18 @@ export function pendingInflight(): InflightEntry[] {
|
|
|
153
243
|
return load().filter((e) => e.state === "inflight")
|
|
154
244
|
}
|
|
155
245
|
|
|
246
|
+
/**
|
|
247
|
+
* 回合 prompt 落库后回填 promptId(修复⑧):后台等待/重启重挂的直答归属
|
|
248
|
+
* 需要「这是哪个回合」的边界锚点,taskId 台账是跨进程唯一可靠载体。
|
|
249
|
+
*/
|
|
250
|
+
export function markInflightPromptId(msgId: string, promptId: string): void {
|
|
251
|
+
if (!promptId) return
|
|
252
|
+
mutate((entries) => {
|
|
253
|
+
const entry = entries.find((e) => e.msgId === msgId && e.state === "inflight")
|
|
254
|
+
if (entry && !entry.promptId) entry.promptId = promptId
|
|
255
|
+
})
|
|
256
|
+
}
|
|
257
|
+
|
|
156
258
|
/** 测试用:清空台账文件状态 */
|
|
157
259
|
export function resetInflightJournal(): void {
|
|
158
260
|
withJournalLock(() => save([]))
|
|
@@ -163,9 +265,15 @@ export function resetInflightJournal(): void {
|
|
|
163
265
|
interface HistoryMessage {
|
|
164
266
|
type?: string
|
|
165
267
|
text?: string
|
|
268
|
+
time?: { created?: number }
|
|
166
269
|
content?: Array<{ type?: string; text?: string }>
|
|
167
270
|
}
|
|
168
271
|
|
|
272
|
+
// 时间锚容差:journal.at = QQ 消息到达时刻,定案实证 prompt user 行落库在秒级内;
|
|
273
|
+
// QQ 服务器时间戳与本地时钟可能偏差,±2 分钟以内只用于「找回那一回合」的兜底,
|
|
274
|
+
// 不足以把别条消息误绑进来(同文4连发间隔 ms 级也包含在窗口内——但它们本就同回合语义)。
|
|
275
|
+
const TIME_ANCHOR_TOLERANCE_MS = 120_000
|
|
276
|
+
|
|
169
277
|
export type InflightClass =
|
|
170
278
|
| { kind: "answered"; answer: string }
|
|
171
279
|
| { kind: "running" }
|
|
@@ -176,10 +284,13 @@ export type InflightClass =
|
|
|
176
284
|
* - answered:找到该用户消息,且其后已有 idle + assistant 正文 → 完整答案在库里没投出,补投
|
|
177
285
|
* - running:找到该用户消息但尚未 idle(无论是否已有流式正文)→ 回合在跑,重挂后台等待
|
|
178
286
|
* - lost:历史里找不到该用户消息 → 消息从未到达 opencode(网关窗口丢失),重派/通知
|
|
179
|
-
*
|
|
287
|
+
* 匹配口径(修复④加锚):①文本探针——user 文本包含台账原文前 50 字(prompt 会加
|
|
288
|
+
* 引用前缀/附件注记,不能全等);②时间锚——文本找不到时按 journal.at ±2min 找
|
|
289
|
+
* user 行。修复 423/429 型误伤:旧逻辑文本探针失配即判 lost 重派,把已答回合
|
|
290
|
+
* 再跑一遍。两个锚都找不到才敢说 lost。
|
|
180
291
|
*/
|
|
181
292
|
export function classifyInflight(
|
|
182
|
-
entry: Pick<InflightEntry, "text"
|
|
293
|
+
entry: Pick<InflightEntry, "text"> & Partial<Pick<InflightEntry, "at">>,
|
|
183
294
|
messages: HistoryMessage[],
|
|
184
295
|
): InflightClass {
|
|
185
296
|
const ordered = [...messages].reverse()
|
|
@@ -203,6 +314,22 @@ export function classifyInflight(
|
|
|
203
314
|
}
|
|
204
315
|
}
|
|
205
316
|
}
|
|
317
|
+
if (userIdx < 0 && entry.at !== undefined) {
|
|
318
|
+
// 修复④时间锚兜底:文本探针失配(引用前缀改写/截断/超长原文)不再轻判 lost——
|
|
319
|
+
// 按到达时刻找回原 user 行;取时间距最近的命中(防 5 连发同文/邻近回合误绑),
|
|
320
|
+
// 距离超过容差仍视为找不到。
|
|
321
|
+
let bestIdx = -1
|
|
322
|
+
let bestDelta = Number.POSITIVE_INFINITY
|
|
323
|
+
for (let i = ordered.length - 1; i >= 0; i--) {
|
|
324
|
+
if (ordered[i].type !== "user") continue
|
|
325
|
+
const delta = Math.abs((ordered[i].time?.created ?? 0) - entry.at)
|
|
326
|
+
if (delta < bestDelta) {
|
|
327
|
+
bestDelta = delta
|
|
328
|
+
bestIdx = i
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
if (bestIdx >= 0 && bestDelta <= TIME_ANCHOR_TOLERANCE_MS) userIdx = bestIdx
|
|
332
|
+
}
|
|
206
333
|
if (userIdx < 0) return { kind: "lost" }
|
|
207
334
|
|
|
208
335
|
// 回合边界 = 原用户消息之后、下一条用户消息之前。后续新回合的 idle/答案
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
// - 抢锁失败时看 mtime:超 30s 未刷新判僵尸锁(宿主崩溃)→ 删除强抢
|
|
10
10
|
// - 未抢到可进入待命循环,每 5s 重试,宿主退出/暴毙后自动接管
|
|
11
11
|
// 锁文件按 appId 隔离:~/.openqq/openqq-<appId>.lock。
|
|
12
|
-
import { openSync, writeFileSync, closeSync, unlinkSync, statSync, utimesSync, mkdirSync } from "fs"
|
|
12
|
+
import { openSync, readFileSync, writeFileSync, closeSync, unlinkSync, statSync, utimesSync, mkdirSync } from "fs"
|
|
13
13
|
import { join } from "path"
|
|
14
14
|
import { homedir } from "os"
|
|
15
15
|
|
|
@@ -18,6 +18,11 @@ export const INSTANCE_LOCK_DISABLED_ENV = "QQ_INSTANCE_LOCK"
|
|
|
18
18
|
const LOCK_STALE_MS = 30_000 // 30s 无心跳 = 僵尸锁
|
|
19
19
|
const LOCK_UPDATE_MS = 10_000 // 持锁心跳间隔
|
|
20
20
|
const LOCK_RETRY_MS = 5_000 // 待命抢锁间隔
|
|
21
|
+
// 修复⑤(2026-11-03 定案):持锁自检周期。背景=「暗 believer」事故:旧实例
|
|
22
|
+
// 心跳 touch 失败是静默的(锁文件被新实例接管/删除后自己并不知道),双 believer
|
|
23
|
+
// 并存造成同 msgId 并发受理(主链)。自检看锁文件里的 pid:不是自己且进程存活
|
|
24
|
+
// → 本实例是残留,自杀退出;锁文件消失同样说明被强抢 → 自杀。待命态无锁不检。
|
|
25
|
+
const LOCK_SELF_CHECK_MS = 60_000
|
|
21
26
|
|
|
22
27
|
export interface InstanceLock {
|
|
23
28
|
/** 释放锁(清心跳 + 删锁文件),幂等 */
|
|
@@ -66,12 +71,34 @@ export function acquireInstanceLockAt(path: string, staleMs: number = LOCK_STALE
|
|
|
66
71
|
// 测试场景不拖累进程退出
|
|
67
72
|
heartbeat.unref?.()
|
|
68
73
|
|
|
74
|
+
// 修复⑤:60s 周期自检——锁被他人接管/锁文件消失 → 本实例即残留 believer,自杀。
|
|
75
|
+
// 判定只看锁内容里的 pid 与进程存活:pid==自己则继续;锁文件缺失=被强抢流程
|
|
76
|
+
// 接管中,同样不可信 → 退出(watchdog/bot-launcher 会待命,不产生双跑)。
|
|
77
|
+
const selfCheck = setInterval(() => {
|
|
78
|
+
try {
|
|
79
|
+
const holder = (JSON.parse(readFileSync(path, "utf-8")) as { pid?: number }).pid
|
|
80
|
+
if (holder === process.pid) return
|
|
81
|
+
try {
|
|
82
|
+
process.kill(holder!, 0)
|
|
83
|
+
console.error(`[instance-lock] 自检:锁已被 pid=${holder} 持有且进程存活,本实例为残留 believer,自杀退出`)
|
|
84
|
+
process.exit(1)
|
|
85
|
+
} catch {
|
|
86
|
+
/* holder 已死:等待其锁被 stale 逻辑回收,本实例继续自检 */
|
|
87
|
+
}
|
|
88
|
+
} catch {
|
|
89
|
+
console.error("[instance-lock] 自检:锁文件已消失(被接管或强抢流程删除),本实例退出")
|
|
90
|
+
process.exit(1)
|
|
91
|
+
}
|
|
92
|
+
}, LOCK_SELF_CHECK_MS)
|
|
93
|
+
selfCheck.unref?.()
|
|
94
|
+
|
|
69
95
|
let released = false
|
|
70
96
|
return {
|
|
71
97
|
release: () => {
|
|
72
98
|
if (released) return
|
|
73
99
|
released = true
|
|
74
100
|
clearInterval(heartbeat)
|
|
101
|
+
clearInterval(selfCheck)
|
|
75
102
|
try {
|
|
76
103
|
unlinkSync(path)
|
|
77
104
|
} catch {
|