@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,151 +1,212 @@
1
- // @input: fs/path/os(台账落盘)
2
- // @output: recordInflight, settleInflight, pendingInflight, classifyInflight(纯函数供测试),
3
- // resetInflightJournal(测试用), INFLIGHT_MAX_AGE_MS, REDISPATCH_MAX_AGE_MS
4
- // @pos: core - 在途台账(重启换代丢消息修复:QQ 消息派发落账、答复送达销账、启动对账)
5
- //
6
- // 事故背景(2026-10-30,用户实证):bot 重启/网关静默死亡窗口内到达的 QQ 消息
7
- // 丢失无反馈——在途回合状态全在内存,进程换代即蒸发。本模块把"派发→送达"责任
8
- // 落盘到 ~/.openqq/inflight.json,启动时对账恢复(bridge.recoverInflightRounds)。
9
- import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync } from "fs"
10
- import { join } from "path"
11
- import { homedir } from "os"
12
-
13
- export interface InflightEntry {
14
- /** 跟踪键:真实 QQ msgId;重派回合为合成键 redispatch-<sessionId>-<ts> */
15
- msgId: string
16
- userId: string
17
- sessionId: string
18
- /** 用户消息原文(截 300 字,对账匹配与通知展示用) */
19
- text: string
20
- at: number
21
- state: "inflight" | "settled"
22
- }
23
-
24
- // 对账年龄上限:超 24h 的在途账不再追溯(直接清账)。
25
- // 注意:这也是"重派窗口不限时间"的天然上限——重派窗口设得再大,超 24h 的账已清。
26
- export const INFLIGHT_MAX_AGE_MS = 24 * 60 * 60 * 1000
27
- // 丢失消息自动重派窗口(2026-10-30 用户拍板:默认 2 小时,env QQ_REDISPATCH_MAX_AGE_MS
28
- // 可调;0=关闭自动重派一律通知)。窗口内视为"意图仍然新鲜"自动重派;超期只通知请用户
29
- // 重发——防"陈旧意图"在重启时被意外执行。
30
- export function redispatchMaxAgeMs(): number {
31
- const n = Number(process.env.QQ_REDISPATCH_MAX_AGE_MS ?? "7200000")
32
- return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 7_200_000
33
- }
34
-
35
- // 测试可经 QQ_INFLIGHT_FILE 指向临时文件
36
- function journalPath(): string {
37
- return process.env.QQ_INFLIGHT_FILE || join(homedir(), ".openqq", "inflight.json")
38
- }
39
-
40
- let cache: InflightEntry[] | null = null
41
-
42
- function load(): InflightEntry[] {
43
- if (cache) return cache
44
- let entries: InflightEntry[] = []
45
- try {
46
- if (existsSync(journalPath())) {
47
- const raw = JSON.parse(readFileSync(journalPath(), "utf-8"))
48
- if (Array.isArray(raw)) entries = raw
49
- }
50
- } catch {
51
- entries = [] // 损坏即空,不阻塞启动
52
- }
53
- // 修剪:已销账超 24h 的不再保留;有修剪即落盘(防 settled 条目只进不出)
54
- const pruned = entries.filter((e) => e.state === "inflight" || Date.now() - e.at <= INFLIGHT_MAX_AGE_MS)
55
- cache = pruned
56
- if (pruned.length !== entries.length) save()
57
- return cache
58
- }
59
-
60
- function save(): void {
61
- if (!cache) return
62
- try {
63
- const path = journalPath()
64
- mkdirSync(join(path, ".."), { recursive: true })
65
- // 原子写:先写临时文件再改名,防写一半被杀留坏账
66
- const tmp = `${path}.tmp`
67
- writeFileSync(tmp, JSON.stringify(cache, null, 2))
68
- renameSync(tmp, path)
69
- } catch (error) {
70
- console.warn("[inflight] 台账落盘失败:", error instanceof Error ? error.message : error)
71
- }
72
- }
73
-
74
- /** 派发落账:QQ 消息进入 AI 派发管线前调用 */
75
- export function recordInflight(entry: Omit<InflightEntry, "state">): void {
76
- const entries = load()
77
- entries.push({ ...entry, state: "inflight" })
78
- save()
79
- }
80
-
81
- /** 销账:答复已送达(或已转入有接管的后台等待/已给用户终态反馈) */
82
- export function settleInflight(msgId: string): void {
83
- const entry = load().find((e) => e.msgId === msgId && e.state === "inflight")
84
- if (!entry) return
85
- entry.state = "settled"
86
- save()
87
- }
88
-
89
- /** 待对账清单(启动恢复用) */
90
- export function pendingInflight(): InflightEntry[] {
91
- return load().filter((e) => e.state === "inflight")
92
- }
93
-
94
- /** 测试用:清空台账缓存与文件状态 */
95
- export function resetInflightJournal(): void {
96
- cache = []
97
- save()
98
- }
99
-
100
- // —— 对账分类(纯函数)——
101
- // 与 opencode/mirror.ts buildDigest 同源的消息形状(最小依赖,避免跨层 import)。
102
- interface HistoryMessage {
103
- type?: string
104
- text?: string
105
- content?: Array<{ type?: string; text?: string }>
106
- }
107
-
108
- export type InflightClass =
109
- | { kind: "answered"; answer: string }
110
- | { kind: "running" }
111
- | { kind: "lost" }
112
-
113
- /**
114
- * 对账分类:台账条目 × 会话历史 → 该回合的真实状态。
115
- * - answered:历史里找到该用户消息且其后已有 assistant 正文 → 答案在库里没投出,补投
116
- * - running:找到该用户消息但尚无 assistant 正文 → 回合在跑(或被中断),重挂后台等待
117
- * - lost:历史里找不到该用户消息 → 消息从未到达 opencode(网关窗口丢失),重派/通知
118
- * 匹配口径:历史 user 文本包含台账原文前 50 字(prompt 会加引用前缀/附件注记,不能全等)。
119
- */
120
- export function classifyInflight(
121
- entry: Pick<InflightEntry, "text">,
122
- messages: HistoryMessage[],
123
- ): InflightClass {
124
- const ordered = [...messages].reverse()
125
- let lastUserIdx = -1
126
- for (let i = ordered.length - 1; i >= 0; i--) {
127
- if (ordered[i].type === "user") {
128
- lastUserIdx = i
129
- break
130
- }
131
- }
132
- if (lastUserIdx < 0) return { kind: "lost" }
133
-
134
- const userText = (ordered[lastUserIdx].text ?? "").trim()
135
- const probe = entry.text.trim().slice(0, 50)
136
- // 纯附件消息(无文字)无法文本匹配——探针为空视为匹配(由 answered 判定兜底)
137
- const matched = probe === "" || userText.includes(probe)
138
- if (!matched) return { kind: "lost" }
139
-
140
- const answerParts: string[] = []
141
- for (let i = lastUserIdx + 1; i < ordered.length; i++) {
142
- const m = ordered[i]
143
- if (m.type === "assistant") {
144
- for (const p of m.content ?? []) {
145
- if (p.type === "text" && p.text?.trim()) answerParts.push(p.text.trim())
146
- }
147
- }
148
- }
149
- const answer = answerParts.join("\n").trim()
150
- return answer ? { kind: "answered", answer } : { kind: "running" }
151
- }
1
+ // @input: fs/path/os(台账落盘)
2
+ // @output: claimInflight, recordInflight, settleInflight, pendingInflight, classifyInflight(纯函数供测试),
3
+ // resetInflightJournal(测试用), INFLIGHT_MAX_AGE_MS, REDISPATCH_MAX_AGE_MS
4
+ // @pos: core - 在途台账(重启换代丢消息修复:QQ 消息派发落账、答复送达销账、启动对账)
5
+ //
6
+ // 事故背景(2026-10-30,用户实证):bot 重启/网关静默死亡窗口内到达的 QQ 消息
7
+ // 丢失无反馈——在途回合状态全在内存,进程换代即蒸发。本模块把"派发→送达"责任
8
+ // 落盘到 ~/.openqq/inflight.json,启动时对账恢复(bridge.recoverInflightRounds)。
9
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, openSync, closeSync, unlinkSync, statSync } from "fs"
10
+ import { join } from "path"
11
+ import { homedir } from "os"
12
+
13
+ export interface InflightEntry {
14
+ /** 跟踪键:真实 QQ msgId;重派回合为合成键 redispatch-<sessionId>-<ts> */
15
+ msgId: string
16
+ userId: string
17
+ sessionId: string
18
+ /** 用户消息原文(截 300 字,对账匹配与通知展示用) */
19
+ text: string
20
+ at: number
21
+ state: "inflight" | "settled"
22
+ }
23
+
24
+ // 对账年龄上限:超 24h 的在途账不再追溯(直接清账)。
25
+ // 注意:这也是"重派窗口不限时间"的天然上限——重派窗口设得再大,超 24h 的账已清。
26
+ export const INFLIGHT_MAX_AGE_MS = 24 * 60 * 60 * 1000
27
+ // 丢失消息自动重派窗口(2026-10-30 用户拍板:默认 2 小时,env QQ_REDISPATCH_MAX_AGE_MS
28
+ // 可调;0=关闭自动重派一律通知)。窗口内视为"意图仍然新鲜"自动重派;超期只通知请用户
29
+ // 重发——防"陈旧意图"在重启时被意外执行。
30
+ export function redispatchMaxAgeMs(): number {
31
+ const n = Number(process.env.QQ_REDISPATCH_MAX_AGE_MS ?? "7200000")
32
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 7_200_000
33
+ }
34
+
35
+ // 测试可经 QQ_INFLIGHT_FILE 指向临时文件
36
+ function journalPath(): string {
37
+ return process.env.QQ_INFLIGHT_FILE || join(homedir(), ".openqq", "inflight.json")
38
+ }
39
+
40
+ function load(): InflightEntry[] {
41
+ let entries: InflightEntry[] = []
42
+ try {
43
+ if (existsSync(journalPath())) {
44
+ const raw = JSON.parse(readFileSync(journalPath(), "utf-8"))
45
+ if (Array.isArray(raw)) entries = raw
46
+ }
47
+ } catch {
48
+ entries = [] // 损坏即空,不阻塞启动
49
+ }
50
+ // 读取始终走磁盘:多个 bot 执行体可能共享台账,进程内 cache 会看不到彼此的认领。
51
+ return entries.filter((e) => e.state === "inflight" || Date.now() - e.at <= INFLIGHT_MAX_AGE_MS)
52
+ }
53
+
54
+ function save(entries: InflightEntry[]): void {
55
+ const path = journalPath()
56
+ mkdirSync(join(path, ".."), { recursive: true })
57
+ // 临时文件带进程与随机后缀:并发执行体不会互相覆盖对方的 tmp。
58
+ const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
59
+ try {
60
+ writeFileSync(tmp, JSON.stringify(entries, null, 2), { mode: 0o600 }) // 台账含用户消息,POSIX 仅本人可读
61
+ renameSync(tmp, path)
62
+ } catch (error) {
63
+ try { unlinkSync(tmp) } catch { /* 已改名或清理失败 */ }
64
+ throw error
65
+ }
66
+ }
67
+
68
+ // 所有台账 mutation 共用一把短临界区文件锁。仅原子 rename 不够:两个进程仍可能
69
+ // 基于各自旧快照互相覆盖。锁内重新读盘,保证跨进程 claim/settle 不丢更新。
70
+ const JOURNAL_LOCK_STALE_MS = 30_000
71
+ const JOURNAL_LOCK_WAIT_MS = 5_000
72
+ const sleepArray = new Int32Array(new SharedArrayBuffer(4))
73
+
74
+ function withJournalLock<T>(fn: () => T): T {
75
+ const path = journalPath()
76
+ mkdirSync(join(path, ".."), { recursive: true })
77
+ const lockPath = `${path}.lock`
78
+ const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`
79
+ const deadline = Date.now() + JOURNAL_LOCK_WAIT_MS
80
+ for (;;) {
81
+ try {
82
+ const fd = openSync(lockPath, "wx", 0o600)
83
+ try {
84
+ writeFileSync(fd, token)
85
+ } finally {
86
+ closeSync(fd)
87
+ }
88
+ break
89
+ } catch (error) {
90
+ try {
91
+ if (Date.now() - statSync(lockPath).mtimeMs > JOURNAL_LOCK_STALE_MS) unlinkSync(lockPath)
92
+ } catch { /* 锁不存在/另一进程正在接管,下轮重试 */ }
93
+ if (Date.now() >= deadline) {
94
+ throw new Error(`在途台账锁等待超时: ${error instanceof Error ? error.message : error}`)
95
+ }
96
+ Atomics.wait(sleepArray, 0, 0, 10)
97
+ }
98
+ }
99
+
100
+ try {
101
+ return fn()
102
+ } finally {
103
+ // 只释放自己持有的锁; stale 接管后,旧持有者不能误删新锁。
104
+ try {
105
+ if (readFileSync(lockPath, "utf-8") === token) unlinkSync(lockPath)
106
+ } catch { /* 已被 stale 清理 */ }
107
+ }
108
+ }
109
+
110
+ function mutate<T>(fn: (entries: InflightEntry[]) => T): T {
111
+ return withJournalLock(() => {
112
+ const entries = load()
113
+ const result = fn(entries)
114
+ save(entries)
115
+ return result
116
+ })
117
+ }
118
+
119
+ /**
120
+ * AI 派发前原子认领。真实 QQ msgId 无论在途或已销账,都拒绝再次执行;
121
+ * 这把网关的进程内 Set 去重提升为跨进程/重启的 durable gate。
122
+ */
123
+ export function claimInflight(entry: Omit<InflightEntry, "state">): boolean {
124
+ return mutate((entries) => {
125
+ if (entries.some((e) => e.msgId === entry.msgId)) return false
126
+ entries.push({ ...entry, state: "inflight" })
127
+ return true
128
+ })
129
+ }
130
+
131
+ /** 派发落账:同 msgId 幂等;sessionId 允许后补(入队时未知、drain 时回填) */
132
+ export function recordInflight(entry: Omit<InflightEntry, "state">): void {
133
+ mutate((entries) => {
134
+ const existing = entries.find((e) => e.msgId === entry.msgId)
135
+ if (existing) {
136
+ if (!existing.sessionId && entry.sessionId) existing.sessionId = entry.sessionId
137
+ return
138
+ }
139
+ entries.push({ ...entry, state: "inflight" })
140
+ })
141
+ }
142
+
143
+ /** 销账:答复已送达(或已转入有接管的后台等待/已给用户终态反馈) */
144
+ export function settleInflight(msgId: string): void {
145
+ mutate((entries) => {
146
+ const entry = entries.find((e) => e.msgId === msgId && e.state === "inflight")
147
+ if (entry) entry.state = "settled"
148
+ })
149
+ }
150
+
151
+ /** 待对账清单(启动恢复用) */
152
+ export function pendingInflight(): InflightEntry[] {
153
+ return load().filter((e) => e.state === "inflight")
154
+ }
155
+
156
+ /** 测试用:清空台账文件状态 */
157
+ export function resetInflightJournal(): void {
158
+ withJournalLock(() => save([]))
159
+ }
160
+
161
+ // —— 对账分类(纯函数)——
162
+ // 与 opencode/mirror.ts buildDigest 同源的消息形状(最小依赖,避免跨层 import)。
163
+ interface HistoryMessage {
164
+ type?: string
165
+ text?: string
166
+ content?: Array<{ type?: string; text?: string }>
167
+ }
168
+
169
+ export type InflightClass =
170
+ | { kind: "answered"; answer: string }
171
+ | { kind: "running" }
172
+ | { kind: "lost" }
173
+
174
+ /**
175
+ * 对账分类:台账条目 × 会话历史 → 该回合的真实状态。
176
+ * - answered:历史里找到该用户消息且其后已有 assistant 正文 → 答案在库里没投出,补投
177
+ * - running:找到该用户消息但尚无 assistant 正文 → 回合在跑(或被中断),重挂后台等待
178
+ * - lost:历史里找不到该用户消息 → 消息从未到达 opencode(网关窗口丢失),重派/通知
179
+ * 匹配口径:历史 user 文本包含台账原文前 50 字(prompt 会加引用前缀/附件注记,不能全等)。
180
+ */
181
+ export function classifyInflight(
182
+ entry: Pick<InflightEntry, "text">,
183
+ messages: HistoryMessage[],
184
+ ): InflightClass {
185
+ const ordered = [...messages].reverse()
186
+ let lastUserIdx = -1
187
+ for (let i = ordered.length - 1; i >= 0; i--) {
188
+ if (ordered[i].type === "user") {
189
+ lastUserIdx = i
190
+ break
191
+ }
192
+ }
193
+ if (lastUserIdx < 0) return { kind: "lost" }
194
+
195
+ const userText = (ordered[lastUserIdx].text ?? "").trim()
196
+ const probe = entry.text.trim().slice(0, 50)
197
+ // 纯附件消息(无文字)无法文本匹配——探针为空视为匹配(由 answered 判定兜底)
198
+ const matched = probe === "" || userText.includes(probe)
199
+ if (!matched) return { kind: "lost" }
200
+
201
+ const answerParts: string[] = []
202
+ for (let i = lastUserIdx + 1; i < ordered.length; i++) {
203
+ const m = ordered[i]
204
+ if (m.type === "assistant") {
205
+ for (const p of m.content ?? []) {
206
+ if (p.type === "text" && p.text?.trim()) answerParts.push(p.text.trim())
207
+ }
208
+ }
209
+ }
210
+ const answer = answerParts.join("\n").trim()
211
+ return answer ? { kind: "answered", answer } : { kind: "running" }
212
+ }
@@ -1,122 +1,122 @@
1
- // @input: fs/path/os(锁文件读写)
2
- // @output: acquireInstanceLock, acquireInstanceLockAt(测试用), waitInstanceLock, INSTANCE_LOCK_DISABLED_ENV
3
- // @pos: core - 单实例锁(防多开:双实例互踩 QQ 网关会互踢下线)
4
- //
5
- // M 项(2026-10-30,方案吸收竞品 opencode-qq-v2 的 proper-lockfile 设计,
6
- // 零依赖手写以守"官方/三方包不进 dependencies"红线):
7
- // - wx 原子创建锁文件(含 pid+启动时间),抢到即宿主
8
- // - 持锁者每 10s 刷新 mtime 作心跳
9
- // - 抢锁失败时看 mtime:超 30s 未刷新判僵尸锁(宿主崩溃)→ 删除强抢
10
- // - 未抢到可进入待命循环,每 5s 重试,宿主退出/暴毙后自动接管
11
- // 锁文件按 appId 隔离:~/.openqq/openqq-<appId>.lock。
12
- import { openSync, writeFileSync, closeSync, unlinkSync, statSync, utimesSync, mkdirSync } from "fs"
13
- import { join } from "path"
14
- import { homedir } from "os"
15
-
16
- export const INSTANCE_LOCK_DISABLED_ENV = "QQ_INSTANCE_LOCK"
17
-
18
- const LOCK_STALE_MS = 30_000 // 30s 无心跳 = 僵尸锁
19
- const LOCK_UPDATE_MS = 10_000 // 持锁心跳间隔
20
- const LOCK_RETRY_MS = 5_000 // 待命抢锁间隔
21
-
22
- export interface InstanceLock {
23
- /** 释放锁(清心跳 + 删锁文件),幂等 */
24
- release: () => void
25
- }
26
-
27
- function lockPathOf(appId: string): string {
28
- return join(homedir(), ".openqq", `openqq-${appId}.lock`)
29
- }
30
-
31
- function touch(path: string): void {
32
- const now = new Date()
33
- utimesSync(path, now, now)
34
- }
35
-
36
- /** 尝试抢锁一次(显式路径版,导出供测试);成功返回 InstanceLock,被占/异常返回 null */
37
- export function acquireInstanceLockAt(path: string, staleMs: number = LOCK_STALE_MS): InstanceLock | null {
38
- try {
39
- mkdirSync(join(path, ".."), { recursive: true })
40
- // wx = 原子排他创建,已存在则抛 EEXIST
41
- const fd = openSync(path, "wx")
42
- writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }))
43
- closeSync(fd)
44
- } catch {
45
- // 已存在:看 mtime 判僵尸(宿主崩溃没来得及释放)
46
- try {
47
- const age = Date.now() - statSync(path).mtimeMs
48
- if (age <= staleMs) return null // 活着的宿主持有
49
- unlinkSync(path) // 僵尸锁,强抢
50
- const fd = openSync(path, "wx")
51
- writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now(), tookOverStale: true }))
52
- closeSync(fd)
53
- console.warn(`[instance-lock] 检测到僵尸锁(${Math.round(age / 1000)}s 无心跳),已接管`)
54
- } catch {
55
- return null // 竞态(另一实例先抢)/文件系统异常 → 视为被占
56
- }
57
- }
58
-
59
- const heartbeat = setInterval(() => {
60
- try {
61
- touch(path)
62
- } catch {
63
- /* 锁文件被外部删除时心跳失败,下轮仍试;不致命 */
64
- }
65
- }, LOCK_UPDATE_MS)
66
- // 测试场景不拖累进程退出
67
- heartbeat.unref?.()
68
-
69
- let released = false
70
- return {
71
- release: () => {
72
- if (released) return
73
- released = true
74
- clearInterval(heartbeat)
75
- try {
76
- unlinkSync(path)
77
- } catch {
78
- /* 已被接管/删除 */
79
- }
80
- },
81
- }
82
- }
83
-
84
- /** 尝试抢锁一次;成功返回 InstanceLock,被占/异常返回 null */
85
- export function acquireInstanceLock(appId: string): InstanceLock | null {
86
- return acquireInstanceLockAt(lockPathOf(appId))
87
- }
88
-
89
- /** 观测锁活性(不抢锁):锁文件存在且心跳新鲜 = bot 活着。插件引导器用。 */
90
- export function isInstanceAlive(appId: string, staleMs: number = LOCK_STALE_MS): boolean {
91
- return isInstanceAliveAt(lockPathOf(appId), staleMs)
92
- }
93
-
94
- /** 显式路径版存活观测(导出供测试) */
95
- export function isInstanceAliveAt(path: string, staleMs: number = LOCK_STALE_MS): boolean {
96
- try {
97
- return Date.now() - statSync(path).mtimeMs <= staleMs
98
- } catch {
99
- return false
100
- }
101
- }
102
-
103
- // 待命日志节流(2026-10-30 清债 P3):首次 + 之后每 120 次(=10 分钟)打一条,
104
- // 长期待命不刷爆日志。纯函数导出供测试。
105
- export function shouldLogStandby(attempt: number): boolean {
106
- return attempt === 0 || attempt % 120 === 0
107
- }
108
-
109
- /**
110
- * 阻塞式抢锁:抢不到就每 5s 重试,直到成为宿主。
111
- * 用于启动入口——双开时后到实例待命,宿主退出后自动接管。
112
- */
113
- export async function waitInstanceLock(appId: string): Promise<InstanceLock> {
114
- for (let attempt = 0; ; attempt++) {
115
- const lock = acquireInstanceLock(appId)
116
- if (lock) return lock
117
- if (shouldLogStandby(attempt)) {
118
- console.log(`[instance-lock] 已有实例在运行,本实例待命(每 ${LOCK_RETRY_MS / 1000}s 重试抢锁,日志已节流)`)
119
- }
120
- await new Promise((r) => setTimeout(r, LOCK_RETRY_MS))
121
- }
122
- }
1
+ // @input: fs/path/os(锁文件读写)
2
+ // @output: acquireInstanceLock, acquireInstanceLockAt(测试用), waitInstanceLock, INSTANCE_LOCK_DISABLED_ENV
3
+ // @pos: core - 单实例锁(防多开:双实例互踩 QQ 网关会互踢下线)
4
+ //
5
+ // M 项(2026-10-30,方案吸收竞品 opencode-qq-v2 的 proper-lockfile 设计,
6
+ // 零依赖手写以守"官方/三方包不进 dependencies"红线):
7
+ // - wx 原子创建锁文件(含 pid+启动时间),抢到即宿主
8
+ // - 持锁者每 10s 刷新 mtime 作心跳
9
+ // - 抢锁失败时看 mtime:超 30s 未刷新判僵尸锁(宿主崩溃)→ 删除强抢
10
+ // - 未抢到可进入待命循环,每 5s 重试,宿主退出/暴毙后自动接管
11
+ // 锁文件按 appId 隔离:~/.openqq/openqq-<appId>.lock。
12
+ import { openSync, writeFileSync, closeSync, unlinkSync, statSync, utimesSync, mkdirSync } from "fs"
13
+ import { join } from "path"
14
+ import { homedir } from "os"
15
+
16
+ export const INSTANCE_LOCK_DISABLED_ENV = "QQ_INSTANCE_LOCK"
17
+
18
+ const LOCK_STALE_MS = 30_000 // 30s 无心跳 = 僵尸锁
19
+ const LOCK_UPDATE_MS = 10_000 // 持锁心跳间隔
20
+ const LOCK_RETRY_MS = 5_000 // 待命抢锁间隔
21
+
22
+ export interface InstanceLock {
23
+ /** 释放锁(清心跳 + 删锁文件),幂等 */
24
+ release: () => void
25
+ }
26
+
27
+ function lockPathOf(appId: string): string {
28
+ return join(homedir(), ".openqq", `openqq-${appId}.lock`)
29
+ }
30
+
31
+ function touch(path: string): void {
32
+ const now = new Date()
33
+ utimesSync(path, now, now)
34
+ }
35
+
36
+ /** 尝试抢锁一次(显式路径版,导出供测试);成功返回 InstanceLock,被占/异常返回 null */
37
+ export function acquireInstanceLockAt(path: string, staleMs: number = LOCK_STALE_MS): InstanceLock | null {
38
+ try {
39
+ mkdirSync(join(path, ".."), { recursive: true })
40
+ // wx = 原子排他创建,已存在则抛 EEXIST
41
+ const fd = openSync(path, "wx")
42
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }))
43
+ closeSync(fd)
44
+ } catch {
45
+ // 已存在:看 mtime 判僵尸(宿主崩溃没来得及释放)
46
+ try {
47
+ const age = Date.now() - statSync(path).mtimeMs
48
+ if (age <= staleMs) return null // 活着的宿主持有
49
+ unlinkSync(path) // 僵尸锁,强抢
50
+ const fd = openSync(path, "wx")
51
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now(), tookOverStale: true }))
52
+ closeSync(fd)
53
+ console.warn(`[instance-lock] 检测到僵尸锁(${Math.round(age / 1000)}s 无心跳),已接管`)
54
+ } catch {
55
+ return null // 竞态(另一实例先抢)/文件系统异常 → 视为被占
56
+ }
57
+ }
58
+
59
+ const heartbeat = setInterval(() => {
60
+ try {
61
+ touch(path)
62
+ } catch {
63
+ /* 锁文件被外部删除时心跳失败,下轮仍试;不致命 */
64
+ }
65
+ }, LOCK_UPDATE_MS)
66
+ // 测试场景不拖累进程退出
67
+ heartbeat.unref?.()
68
+
69
+ let released = false
70
+ return {
71
+ release: () => {
72
+ if (released) return
73
+ released = true
74
+ clearInterval(heartbeat)
75
+ try {
76
+ unlinkSync(path)
77
+ } catch {
78
+ /* 已被接管/删除 */
79
+ }
80
+ },
81
+ }
82
+ }
83
+
84
+ /** 尝试抢锁一次;成功返回 InstanceLock,被占/异常返回 null */
85
+ export function acquireInstanceLock(appId: string): InstanceLock | null {
86
+ return acquireInstanceLockAt(lockPathOf(appId))
87
+ }
88
+
89
+ /** 观测锁活性(不抢锁):锁文件存在且心跳新鲜 = bot 活着。插件引导器用。 */
90
+ export function isInstanceAlive(appId: string, staleMs: number = LOCK_STALE_MS): boolean {
91
+ return isInstanceAliveAt(lockPathOf(appId), staleMs)
92
+ }
93
+
94
+ /** 显式路径版存活观测(导出供测试) */
95
+ export function isInstanceAliveAt(path: string, staleMs: number = LOCK_STALE_MS): boolean {
96
+ try {
97
+ return Date.now() - statSync(path).mtimeMs <= staleMs
98
+ } catch {
99
+ return false
100
+ }
101
+ }
102
+
103
+ // 待命日志节流(2026-10-30 清债 P3):首次 + 之后每 120 次(=10 分钟)打一条,
104
+ // 长期待命不刷爆日志。纯函数导出供测试。
105
+ export function shouldLogStandby(attempt: number): boolean {
106
+ return attempt === 0 || attempt % 120 === 0
107
+ }
108
+
109
+ /**
110
+ * 阻塞式抢锁:抢不到就每 5s 重试,直到成为宿主。
111
+ * 用于启动入口——双开时后到实例待命,宿主退出后自动接管。
112
+ */
113
+ export async function waitInstanceLock(appId: string): Promise<InstanceLock> {
114
+ for (let attempt = 0; ; attempt++) {
115
+ const lock = acquireInstanceLock(appId)
116
+ if (lock) return lock
117
+ if (shouldLogStandby(attempt)) {
118
+ console.log(`[instance-lock] 已有实例在运行,本实例待命(每 ${LOCK_RETRY_MS / 1000}s 重试抢锁,日志已节流)`)
119
+ }
120
+ await new Promise((r) => setTimeout(r, LOCK_RETRY_MS))
121
+ }
122
+ }