@linjz/opencode-qqbot 0.3.15 → 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 +42 -5
- package/bin/openqq.js +13 -0
- package/dist/notify-cli.js +28 -14
- package/dist/opencode-qqbot-plugin.js +934 -64
- package/dist/openqq-bot.js +3095 -677
- package/dist/openqq-cli.js +791 -0
- package/dist/openqq-watchdog.js +1063 -0
- package/package.json +8 -5
- package/src/bridge.ts +1310 -150
- package/src/cli/notify.ts +167 -158
- 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 +85 -0
- 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 +14 -5
- 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 +10 -2
- 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 -96
- package/src/core/outbox.ts +10 -9
- package/src/core/permission.ts +627 -303
- 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 -115
- package/src/qq/api.ts +165 -61
- package/src/qq/gateway.ts +79 -16
- package/src/qq/sender.ts +30 -18
- package/src/qq/types.ts +7 -0
package/src/core/send-media.ts
CHANGED
|
@@ -22,6 +22,34 @@ export function allowedSendRoots(extraEnv = process.env.QQ_SEND_EXTRA_ROOTS): st
|
|
|
22
22
|
return roots.map((r) => resolve(r))
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
// DEF-qqbot-20261112-03(owner 2026-11-14「全修剩下缺陷」批):
|
|
26
|
+
// 白名单是目录级粒度——`..\..\..` 穿越解析后落进白名单根(实测投递 .env 825B 文件卡)。
|
|
27
|
+
// 文件级拒绝名单兜底:**无论落在哪个白名单根内,密钥/凭据类文件绝不外发**(拒绝优先于白名单)。
|
|
28
|
+
/** 精确拒绝的文件名(小写比较) */
|
|
29
|
+
export const SEND_DENIED_NAMES = new Set([
|
|
30
|
+
".env",
|
|
31
|
+
"credentials",
|
|
32
|
+
"secrets",
|
|
33
|
+
"id_rsa",
|
|
34
|
+
"id_dsa",
|
|
35
|
+
"id_ecdsa",
|
|
36
|
+
"id_ed25519",
|
|
37
|
+
".npmrc",
|
|
38
|
+
".pypirc",
|
|
39
|
+
"netrc",
|
|
40
|
+
])
|
|
41
|
+
/** 拒绝的扩展名(小写比较,密钥/证书/凭据存储类) */
|
|
42
|
+
const SEND_DENIED_EXTS = new Set([".pem", ".key", ".p12", ".pfx", ".kdbx", ".htpasswd"])
|
|
43
|
+
|
|
44
|
+
/** 文件级拒绝校验(DEF-qqbot-20261112-03):basename 命中即拒,优先于目录白名单。 */
|
|
45
|
+
export function isDeniedSendFile(filePath: string): boolean {
|
|
46
|
+
const name = basename(filePath).toLowerCase()
|
|
47
|
+
if (SEND_DENIED_NAMES.has(name)) return true
|
|
48
|
+
if (name.startsWith(".env.") || name.startsWith(".env-")) return true
|
|
49
|
+
const ext = extname(name)
|
|
50
|
+
return SEND_DENIED_EXTS.has(ext)
|
|
51
|
+
}
|
|
52
|
+
|
|
25
53
|
/** 路径白名单校验:规范化后必须落在某个允许根目录内(分隔符按平台自适应) */
|
|
26
54
|
export function isAllowedSendPath(filePath: string, roots = allowedSendRoots()): boolean {
|
|
27
55
|
const full = resolve(filePath.trim().replace(/^"|"$/g, ""))
|
|
@@ -64,6 +92,10 @@ export async function sendLocalFile(
|
|
|
64
92
|
deps: SendLocalFileDeps,
|
|
65
93
|
): Promise<string> {
|
|
66
94
|
const trimmed = filePath.trim()
|
|
95
|
+
// DEF-qqbot-20261112-03:文件级拒绝优先于目录白名单(穿越解析落白名单根也拦)
|
|
96
|
+
if (isDeniedSendFile(trimmed)) {
|
|
97
|
+
throw new Error("该文件属于密钥/凭据类,禁止外发(已拦截)")
|
|
98
|
+
}
|
|
67
99
|
if (!isAllowedSendPath(trimmed)) {
|
|
68
100
|
throw new Error(`路径不在白名单(仅允许:${allowedSendRoots().join("、")};可加 QQ_SEND_EXTRA_ROOTS)`)
|
|
69
101
|
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// @input: process.env(QQ_DATA_DIR)、appId(可选)
|
|
2
|
+
// @output: storageRoot, storageFile, isMultiRole
|
|
3
|
+
// @pos: core - 数据分桶路径解析(多角色隔离的地基)
|
|
4
|
+
//
|
|
5
|
+
// 多角色改造(2026-11-17,owner 裁定单进程多 bot 身份):
|
|
6
|
+
// - legacy 单角色:一切数据文件照旧在 ~/.openqq/(零迁移,存量部署行为不变);
|
|
7
|
+
// - 多角色(QQ_BOTS 配置了 ≥1 个角色):每个角色的运行时文件落在
|
|
8
|
+
// ~/.openqq/roles/<appId>/ 子目录——gateway-state(RESUME 会话/seq)、
|
|
9
|
+
// inflight 台账、pending-permissions、forms、quota、sessions 映射等
|
|
10
|
+
// 按角色物理隔离,杜绝两角色互踩(11-17 实证:135 上两实例共享
|
|
11
|
+
// ~/.openqq 互踩隐患)。
|
|
12
|
+
// - 进程级共享文件不走路由:heartbeat、openqq.log、supervisor 台账、
|
|
13
|
+
// .env 本体、incident.json(引擎侧事故留痕,跨角色一份更合理)。
|
|
14
|
+
// 设计取舍:不用 AsyncLocalStorage 隐式传角色——ALS 在个别异步边界丢上下文
|
|
15
|
+
// 的失效模式是「静默写错角色的文件」,比显式传参危险;本模块只做纯路径解析,
|
|
16
|
+
// 角色归属由调用方显式传入。
|
|
17
|
+
import { homedir } from "os"
|
|
18
|
+
import { join } from "path"
|
|
19
|
+
|
|
20
|
+
export const LEGACY_ROOT = join(homedir(), ".openqq")
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* 角色数据根目录。appId 为空 = legacy 根(~/.openqq)。
|
|
24
|
+
* QQ_DATA_DIR env 可整体重定向(测试/容器场景),角色子目录挂在其下。
|
|
25
|
+
*/
|
|
26
|
+
export function storageRoot(appId?: string): string {
|
|
27
|
+
const base = (process.env.QQ_DATA_DIR ?? "").trim() || LEGACY_ROOT
|
|
28
|
+
return appId ? join(base, "roles", appId) : base
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 角色作用域下的具名数据文件路径。appId 为空时退化为 legacy 路径。 */
|
|
32
|
+
export function storageFile(name: string, appId?: string): string {
|
|
33
|
+
return join(storageRoot(appId), name)
|
|
34
|
+
}
|
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
// @input: ~/.openqq 锁文件与心跳文件、process 存活探测、注入的 spawn/kill
|
|
2
|
+
// @output: botWatchdogPaths, readBotHealth, isPidAlive, decideWatchdog, healOnce
|
|
3
|
+
// @pos: core - 跨平台看门狗(纯 Node API,无 PowerShell/OS 脚本依赖)
|
|
4
|
+
//
|
|
5
|
+
// 2026-11-09 架构红线(见 AGENTS.md):运维代码只随插件包分发、只用 TS/JS,
|
|
6
|
+
// 平台差异只允许出现在「自启注册」一处。判活优先级:
|
|
7
|
+
// 锁文件 pid(单实例仲裁的唯一真相)+ process.kill(pid,0) + 心跳文件新鲜度。
|
|
8
|
+
// 约定:锁 mtime 由 bot 每 10s 刷新(instance-lock);心跳文件由 bot 每 60s 刷新,
|
|
9
|
+
// 且 2026-11-09 起「抢锁后立即写」,因此「进程活但心跳陈旧」= 真僵死,不是启动中。
|
|
10
|
+
import { readFileSync, statSync, unlinkSync, writeFileSync } from "fs"
|
|
11
|
+
import { join } from "path"
|
|
12
|
+
import { homedir } from "os"
|
|
13
|
+
|
|
14
|
+
/** 心跳超过 5 分钟未刷新 = 事件循环僵死(与既有看门狗阈值一致) */
|
|
15
|
+
export const HEARTBEAT_STALE_MS = 5 * 60_000
|
|
16
|
+
/** P10:锁 mtime 新鲜阈值(instance-lock 持锁者 10s 刷新;30s=3 倍周期余量)。 */
|
|
17
|
+
export const LOCK_MTIME_FRESH_MS = 30_000
|
|
18
|
+
/** 锁 mtime 超过 30s 未刷新 = 僵尸锁(与 instance-lock 一致) */
|
|
19
|
+
export const LOCK_STALE_MS = 30_000
|
|
20
|
+
/** 启动宽限:锁刚建立、心跳尚未落盘的窗口 */
|
|
21
|
+
export const STARTUP_GRACE_MS = 60_000
|
|
22
|
+
|
|
23
|
+
export interface BotWatchdogPaths {
|
|
24
|
+
lockPath: string
|
|
25
|
+
heartbeatPath: string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function botWatchdogPaths(appId: string): BotWatchdogPaths {
|
|
29
|
+
const dir = join(homedir(), ".openqq")
|
|
30
|
+
return { lockPath: join(dir, `openqq-${appId}.lock`), heartbeatPath: join(dir, "heartbeat") }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface BotHealth {
|
|
34
|
+
/** 锁文件里的 pid;无锁/损坏为 null */
|
|
35
|
+
lockPid: number | null
|
|
36
|
+
/** 锁 mtime 距今毫秒;无锁为 null */
|
|
37
|
+
lockAgeMs: number | null
|
|
38
|
+
/** pid 是否存活;pid 未知为 null */
|
|
39
|
+
pidAlive: boolean | null
|
|
40
|
+
/** 心跳文件距今毫秒;缺失为 null */
|
|
41
|
+
heartbeatAgeMs: number | null
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface WatchdogDecision {
|
|
45
|
+
action: "ok" | "restart"
|
|
46
|
+
reason: string
|
|
47
|
+
/** restart 时若进程仍活着,需要先杀掉的 pid */
|
|
48
|
+
killPid: number | null
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface WatchdogOptions {
|
|
52
|
+
heartbeatStaleMs?: number
|
|
53
|
+
startupGraceMs?: number
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 跨平台进程存活探测:ESRCH=不存在;EPERM=存在但无权限(视为存活) */
|
|
57
|
+
export function isPidAlive(pid: number): boolean {
|
|
58
|
+
if (!Number.isInteger(pid) || pid <= 0) return false
|
|
59
|
+
try {
|
|
60
|
+
process.kill(pid, 0)
|
|
61
|
+
return true
|
|
62
|
+
} catch (error) {
|
|
63
|
+
return (error as NodeJS.ErrnoException).code === "EPERM"
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function ageOf(path: string, now: number): number | null {
|
|
68
|
+
try {
|
|
69
|
+
return Math.max(0, now - statSync(path).mtimeMs)
|
|
70
|
+
} catch {
|
|
71
|
+
return null
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function readBotHealth(paths: BotWatchdogPaths, now = Date.now()): BotHealth {
|
|
76
|
+
const lockAgeMs = ageOf(paths.lockPath, now)
|
|
77
|
+
let lockPid: number | null = null
|
|
78
|
+
if (lockAgeMs !== null) {
|
|
79
|
+
try {
|
|
80
|
+
const raw = JSON.parse(readFileSync(paths.lockPath, "utf-8")) as { pid?: unknown }
|
|
81
|
+
if (typeof raw.pid === "number" && Number.isInteger(raw.pid)) lockPid = raw.pid
|
|
82
|
+
} catch {
|
|
83
|
+
/* 损坏/半写锁 → pid 未知,交给决策当缺失处理 */
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
lockPid,
|
|
88
|
+
lockAgeMs,
|
|
89
|
+
pidAlive: lockPid === null ? null : isPidAlive(lockPid),
|
|
90
|
+
heartbeatAgeMs: ageOf(paths.heartbeatPath, now),
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** 纯决策(表驱动,导出供测试):只回答「要不要重启、要不要先杀谁、为什么」 */
|
|
95
|
+
export function decideWatchdog(h: BotHealth, opts?: WatchdogOptions): WatchdogDecision {
|
|
96
|
+
const heartbeatStaleMs = opts?.heartbeatStaleMs ?? HEARTBEAT_STALE_MS
|
|
97
|
+
const startupGraceMs = opts?.startupGraceMs ?? STARTUP_GRACE_MS
|
|
98
|
+
|
|
99
|
+
if (h.lockPid === null) {
|
|
100
|
+
return {
|
|
101
|
+
action: "restart",
|
|
102
|
+
reason: h.lockAgeMs === null ? "进程缺失(无锁文件)" : "锁文件无可读 pid",
|
|
103
|
+
killPid: null,
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (h.pidAlive === false) {
|
|
107
|
+
return { action: "restart", reason: `锁定进程已退出(pid=${h.lockPid})`, killPid: null }
|
|
108
|
+
}
|
|
109
|
+
if (h.heartbeatAgeMs === null) {
|
|
110
|
+
const lockAge = h.lockAgeMs ?? 0
|
|
111
|
+
if (lockAge < startupGraceMs) {
|
|
112
|
+
return { action: "ok", reason: `启动中(心跳未落盘,锁龄 ${Math.round(lockAge / 1000)}s)`, killPid: null }
|
|
113
|
+
}
|
|
114
|
+
// DEF-20261119-P10 第一层守卫:锁 mtime 由持锁者每 10s 刷新(instance-lock 契约,
|
|
115
|
+
// index.ts 注释明言「锁活性另由 instance-lock 的 mtime 心跳承担」)。锁新鲜=进程
|
|
116
|
+
// 必有进展——heartbeat 文件可能因 IO 抖动/启动边缘未落盘,不得据此杀真 holder。
|
|
117
|
+
// 2026-11-19 实证:CLI/引导器拉起的健康 spawn 被「心跳文件缺失」分支误杀 10+ 次,
|
|
118
|
+
// 锁 mtime 全程新鲜。阈值对齐僵尸锁口径(30s=3×10s 刷新周期)。
|
|
119
|
+
if (h.lockAgeMs !== null && h.lockAgeMs < LOCK_MTIME_FRESH_MS) {
|
|
120
|
+
return {
|
|
121
|
+
action: "ok",
|
|
122
|
+
reason: `锁心跳新鲜(${Math.round(h.lockAgeMs / 1000)}s)——进程有进展,heartbeat 文件缺失不杀`,
|
|
123
|
+
killPid: null,
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return { action: "restart", reason: "心跳文件缺失(进程存活但无进展)", killPid: h.lockPid }
|
|
127
|
+
}
|
|
128
|
+
if (h.heartbeatAgeMs > heartbeatStaleMs) {
|
|
129
|
+
// P10 第二层守卫:同上——heartbeat 文件停滞但锁 mtime 新鲜 = 文件写入链路故障,
|
|
130
|
+
// 进程实际存活,按「无进展」杀属于误杀。锁也陈旧才真是僵死。
|
|
131
|
+
if (h.lockAgeMs !== null && h.lockAgeMs < LOCK_MTIME_FRESH_MS) {
|
|
132
|
+
return {
|
|
133
|
+
action: "ok",
|
|
134
|
+
reason: `锁心跳新鲜(${Math.round(h.lockAgeMs / 1000)}s)——heartbeat 文件停滞按写入故障处理,不杀`,
|
|
135
|
+
killPid: null,
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return {
|
|
139
|
+
action: "restart",
|
|
140
|
+
reason: `心跳陈旧 ${Math.round(h.heartbeatAgeMs / 60_000)} 分钟(进程疑似僵死)`,
|
|
141
|
+
killPid: h.lockPid,
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return { action: "ok", reason: "健康", killPid: null }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export interface HealDeps {
|
|
148
|
+
paths: BotWatchdogPaths
|
|
149
|
+
/** 拉起 bot,返回 pid */
|
|
150
|
+
spawn: () => number
|
|
151
|
+
/** 杀掉残留 pid(默认 process.kill) */
|
|
152
|
+
kill?: (pid: number) => void
|
|
153
|
+
now?: () => number
|
|
154
|
+
log?: (line: string) => void
|
|
155
|
+
opts?: WatchdogOptions
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export interface HealResult {
|
|
159
|
+
action: "ok" | "restart"
|
|
160
|
+
reason: string
|
|
161
|
+
killedPid: number | null
|
|
162
|
+
spawnedPid: number | null
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const defaultKill = (pid: number): void => {
|
|
166
|
+
try {
|
|
167
|
+
process.kill(pid)
|
|
168
|
+
} catch {
|
|
169
|
+
/* 已退出 */
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** 单次巡检:判活 →(必要时)杀残留 → 拉起。副作用全部经注入,便于测试。 */
|
|
174
|
+
export function healOnce(deps: HealDeps): HealResult {
|
|
175
|
+
const now = deps.now?.() ?? Date.now()
|
|
176
|
+
const health = readBotHealth(deps.paths, now)
|
|
177
|
+
const decision = decideWatchdog(health, deps.opts)
|
|
178
|
+
if (decision.action === "ok") return { action: "ok", reason: decision.reason, killedPid: null, spawnedPid: null }
|
|
179
|
+
|
|
180
|
+
let killedPid: number | null = null
|
|
181
|
+
if (decision.killPid !== null && decision.killPid !== process.pid) {
|
|
182
|
+
;(deps.kill ?? defaultKill)(decision.killPid)
|
|
183
|
+
killedPid = decision.killPid
|
|
184
|
+
}
|
|
185
|
+
const spawnedPid = deps.spawn()
|
|
186
|
+
return { action: "restart", reason: decision.reason, killedPid, spawnedPid }
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** 极简 .env 读取(与 bot-launcher.readDotEnvField 同语义;此处避免循环依赖) */
|
|
190
|
+
export function readEnvField(envPath: string, key: string): string | null {
|
|
191
|
+
try {
|
|
192
|
+
for (const line of readFileSync(envPath, "utf-8").split("\n")) {
|
|
193
|
+
const trimmed = line.trim()
|
|
194
|
+
if (!trimmed || trimmed.startsWith("#")) continue
|
|
195
|
+
const eq = trimmed.indexOf("=")
|
|
196
|
+
if (eq < 0) continue
|
|
197
|
+
if (trimmed.slice(0, eq).trim() === key) return trimmed.slice(eq + 1).trim()
|
|
198
|
+
}
|
|
199
|
+
return null
|
|
200
|
+
} catch {
|
|
201
|
+
return null
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** 追加一行巡检日志到 ~/.openqq/watchdog.log(数据目录,不是代码) */
|
|
206
|
+
export function appendWatchdogLog(line: string): void {
|
|
207
|
+
try {
|
|
208
|
+
const dir = join(homedir(), ".openqq")
|
|
209
|
+
writeFileSync(join(dir, "watchdog.log"), `${new Date().toISOString()} ${line}\n`, { flag: "a" })
|
|
210
|
+
} catch {
|
|
211
|
+
/* 日志失败不阻断巡检 */
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// ===== 监督层(2026-11-09 重构,替代裸 healOnce 的「无脑杀旧拉新」)=====
|
|
216
|
+
// 设计对标(当日检索实证):
|
|
217
|
+
// - Erlang OTP supervisor:maximum restart intensity——窗口内重启超限 → 放弃并上报,
|
|
218
|
+
// 「防止同因反复死亡反复重启」;
|
|
219
|
+
// - fleet-guard(Claude Code 生态):升级杀 SIGTERM→宽限→SIGKILL,且 fail-open
|
|
220
|
+
// 「守卫绝不能拖死被守卫者」;
|
|
221
|
+
// - k8s 教训:liveness 误杀瞬时态 → 冷却窗口(冷却期内的重复判死直接跳过);
|
|
222
|
+
// - claude-code#85206:杀掉后必须保留工作并对操作者可感(give-up 必告警)。
|
|
223
|
+
|
|
224
|
+
export interface SupervisorPolicy {
|
|
225
|
+
/** 距上次重启不足该值 → 冷却跳过(防插件引导器与计划任务互踢、防抖动) */
|
|
226
|
+
cooldownMs: number
|
|
227
|
+
/** windowMs 内最多重启次数(OTP intensity) */
|
|
228
|
+
maxRestarts: number
|
|
229
|
+
/** 重启强度统计窗口(OTP period) */
|
|
230
|
+
windowMs: number
|
|
231
|
+
/** SIGTERM 后等待退出的宽限,超时升级强杀(fleet-guard 升级杀) */
|
|
232
|
+
graceMs: number
|
|
233
|
+
/** 监督者认领锁的有效期:持锁期间其他监督者让行 */
|
|
234
|
+
claimTtlMs: number
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export const DEFAULT_SUPERVISOR_POLICY: SupervisorPolicy = {
|
|
238
|
+
cooldownMs: 2 * 60_000,
|
|
239
|
+
maxRestarts: 3,
|
|
240
|
+
windowMs: 15 * 60_000,
|
|
241
|
+
graceMs: 8_000,
|
|
242
|
+
claimTtlMs: 90_000,
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export interface SupervisorState {
|
|
246
|
+
/** 重启时间戳(升序);滑动窗口统计强度 */
|
|
247
|
+
restartLog: number[]
|
|
248
|
+
/** 上次 give-up 告警时间(30 分钟内不重复轰炸操作者) */
|
|
249
|
+
alertedAt?: number
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export type SuperviseAction =
|
|
253
|
+
| { kind: "ok" }
|
|
254
|
+
| { kind: "yield"; reason: string } // 其他监督者持锁
|
|
255
|
+
| { kind: "cooldown"; untilMs: number }
|
|
256
|
+
| { kind: "spawn"; reason: string }
|
|
257
|
+
| { kind: "grace-kill-spawn"; killPid: number; reason: string }
|
|
258
|
+
| { kind: "give-up"; restarts: number }
|
|
259
|
+
|
|
260
|
+
/** 纯决策矩阵(导出供测试):健康 → 强度 → 冷却 → 处置方式。 */
|
|
261
|
+
export function decideSupervise(
|
|
262
|
+
health: BotHealth,
|
|
263
|
+
state: SupervisorState,
|
|
264
|
+
now: number,
|
|
265
|
+
policy: SupervisorPolicy = DEFAULT_SUPERVISOR_POLICY,
|
|
266
|
+
): SuperviseAction {
|
|
267
|
+
const staleHeartbeat = health.heartbeatAgeMs !== null && health.heartbeatAgeMs > HEARTBEAT_STALE_MS
|
|
268
|
+
const needsRestart =
|
|
269
|
+
health.lockPid === null || health.pidAlive === false || staleHeartbeat
|
|
270
|
+
if (!needsRestart) return { kind: "ok" }
|
|
271
|
+
|
|
272
|
+
// OTP intensity:窗口内已达上限 → 放弃循环,上报人工(不给故障进程当永动机)
|
|
273
|
+
const windowStart = now - policy.windowMs
|
|
274
|
+
const recentRestarts = state.restartLog.filter((t) => t > windowStart).length
|
|
275
|
+
if (recentRestarts >= policy.maxRestarts) return { kind: "give-up", restarts: recentRestarts }
|
|
276
|
+
|
|
277
|
+
// 冷却:刚重启过又判死 → 大概率是瞬时/叠加判死,跳过本轮(k8s 误杀教训)
|
|
278
|
+
const last = state.restartLog[state.restartLog.length - 1] ?? null
|
|
279
|
+
if (last !== null && now - last < policy.cooldownMs) return { kind: "cooldown", untilMs: last + policy.cooldownMs }
|
|
280
|
+
|
|
281
|
+
if (health.lockPid !== null && health.pidAlive !== false && staleHeartbeat) {
|
|
282
|
+
return {
|
|
283
|
+
kind: "grace-kill-spawn",
|
|
284
|
+
killPid: health.lockPid,
|
|
285
|
+
reason: `心跳陈旧 ${Math.round((health.heartbeatAgeMs ?? 0) / 60_000)} 分钟(进程活但事件循环无进展)`,
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return { kind: "spawn", reason: health.lockPid === null ? "无实例锁(bot 未运行)" : "锁定进程已退出" }
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
export interface SuperviseDeps {
|
|
292
|
+
paths: BotWatchdogPaths
|
|
293
|
+
spawn: () => number
|
|
294
|
+
policy?: SupervisorPolicy
|
|
295
|
+
/**
|
|
296
|
+
* 触发形态:health-check=周期巡检(默认);manual-restart=openqq restart
|
|
297
|
+
* 人工请求(design §3.9.1:restart 是 superviseOnce 的调用方而非独立实现)。
|
|
298
|
+
* manual-restart 下健康实例也会被优雅杀后拉起,并跳过「杀前复核」(人工意图
|
|
299
|
+
* 即权威,复核只防监督者误杀);强度账/冷却/认领互斥/审计分家全部照旧。
|
|
300
|
+
*/
|
|
301
|
+
request?: "health-check" | "manual-restart"
|
|
302
|
+
now?: () => number
|
|
303
|
+
kill?: (pid: number, signal?: "SIGTERM" | "SIGKILL") => void
|
|
304
|
+
isAlive?: (pid: number) => boolean
|
|
305
|
+
sleep?: (ms: number) => Promise<void>
|
|
306
|
+
log?: (line: string) => void
|
|
307
|
+
/** give-up 时上报操作者(QQ 通知等);缺省只落日志 */
|
|
308
|
+
alert?: (message: string) => void
|
|
309
|
+
statePath?: string
|
|
310
|
+
claimPath?: string
|
|
311
|
+
/** 监督动作审计日志路径(测试注入临时文件,避免污染真实 watchdog.log) */
|
|
312
|
+
auditLogPath?: string
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
export interface SuperviseResult {
|
|
316
|
+
action: string
|
|
317
|
+
detail: string
|
|
318
|
+
killedPid: number | null
|
|
319
|
+
spawnedPid: number | null
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
const defaultSleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))
|
|
323
|
+
const defaultSupervisorKill = (pid: number, signal?: "SIGTERM" | "SIGKILL"): void => {
|
|
324
|
+
try {
|
|
325
|
+
process.kill(pid, signal)
|
|
326
|
+
} catch {
|
|
327
|
+
/* 已退出 */
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function readJson<T>(path: string, fallback: T): T {
|
|
332
|
+
try {
|
|
333
|
+
return { ...fallback, ...(JSON.parse(readFileSync(path, "utf-8")) as T) }
|
|
334
|
+
} catch {
|
|
335
|
+
return fallback
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* 单次监督:认领锁 → 判健康 → 决策 → 执行(优雅杀/拉起/放弃上报)→ 记强度账。
|
|
341
|
+
* 插件引导器与计划任务共用本函数,互斥靠 claim 文件,杜绝双开竞争。
|
|
342
|
+
*/
|
|
343
|
+
export async function superviseOnce(deps: SuperviseDeps): Promise<SuperviseResult> {
|
|
344
|
+
const policy = deps.policy ?? DEFAULT_SUPERVISOR_POLICY
|
|
345
|
+
const now = deps.now?.() ?? Date.now()
|
|
346
|
+
const log = deps.log ?? (() => {})
|
|
347
|
+
const sleep = deps.sleep ?? defaultSleep
|
|
348
|
+
const kill = deps.kill ?? defaultSupervisorKill
|
|
349
|
+
const isAlive = deps.isAlive ?? isPidAlive
|
|
350
|
+
const statePath = deps.statePath ?? join(homedir(), ".openqq", "supervisor.json")
|
|
351
|
+
const claimPath = deps.claimPath ?? join(homedir(), ".openqq", "supervisor.lock")
|
|
352
|
+
const audit = (line: string): void => {
|
|
353
|
+
if (deps.auditLogPath) {
|
|
354
|
+
try {
|
|
355
|
+
writeFileSync(deps.auditLogPath, `${new Date().toISOString()} ${line}\n`, { flag: "a" })
|
|
356
|
+
return
|
|
357
|
+
} catch {
|
|
358
|
+
/* fallthrough 到默认日志 */
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
appendWatchdogLog(line)
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// —— 监督者认领(进程内互斥;持锁者崩溃后 claimTtlMs 可被接管)——
|
|
365
|
+
const claim = readJson<{ pid: number; ts: number }>(claimPath, { pid: 0, ts: 0 })
|
|
366
|
+
if (claim.ts && now - claim.ts < policy.claimTtlMs && claim.pid !== process.pid) {
|
|
367
|
+
return { action: "yield", detail: `监督者 pid=${claim.pid} 持锁中`, killedPid: null, spawnedPid: null }
|
|
368
|
+
}
|
|
369
|
+
try {
|
|
370
|
+
writeFileSync(claimPath, JSON.stringify({ pid: process.pid, ts: now }))
|
|
371
|
+
} catch {
|
|
372
|
+
return { action: "yield", detail: "认领锁不可写", killedPid: null, spawnedPid: null }
|
|
373
|
+
}
|
|
374
|
+
const release = (): void => {
|
|
375
|
+
try {
|
|
376
|
+
writeFileSync(claimPath, JSON.stringify({ pid: 0, ts: 0 }))
|
|
377
|
+
} catch {
|
|
378
|
+
/* 残留由 TTL 接管 */
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
try {
|
|
383
|
+
const health = readBotHealth(deps.paths, now)
|
|
384
|
+
const state = readJson<SupervisorState>(statePath, { restartLog: [] })
|
|
385
|
+
let action = decideSupervise(health, state, now, policy)
|
|
386
|
+
|
|
387
|
+
// 人工请求重启(design §3.9.1 入口 3):健康实例也要优雅杀后拉起;
|
|
388
|
+
// bot 未运行/已死则只拉起。强度与冷却约束在 decideSupervise 内已经生效
|
|
389
|
+
//(needsRestart 为 false 时同样先查 give-up/cooldown,再走到这里覆盖动作)。
|
|
390
|
+
if (deps.request === "manual-restart" && action.kind === "ok") {
|
|
391
|
+
// 强度/冷却约束对人工入口同样生效(design §3.9.1「复用…强度约束」):
|
|
392
|
+
// decideSupervise 的 ok 分支不查强度账,这里补齐同口径检查。
|
|
393
|
+
const windowStart = now - policy.windowMs
|
|
394
|
+
const recentRestarts = state.restartLog.filter((t) => t > windowStart).length
|
|
395
|
+
if (recentRestarts >= policy.maxRestarts) {
|
|
396
|
+
return {
|
|
397
|
+
action: "give-up",
|
|
398
|
+
detail: `15 分钟内已重启 ${recentRestarts} 次(监督强度上限),人工重启亦被拦截,请排查根因`,
|
|
399
|
+
killedPid: null,
|
|
400
|
+
spawnedPid: null,
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
const last = state.restartLog[state.restartLog.length - 1] ?? null
|
|
404
|
+
if (last !== null && now - last < policy.cooldownMs) {
|
|
405
|
+
return { action: "cooldown", detail: `距上次重启不足 ${Math.round(policy.cooldownMs / 1000)}s(冷却期),人工重启跳过`, killedPid: null, spawnedPid: null }
|
|
406
|
+
}
|
|
407
|
+
action =
|
|
408
|
+
health.lockPid !== null && health.pidAlive !== false
|
|
409
|
+
? { kind: "grace-kill-spawn", killPid: health.lockPid, reason: "人工请求重启(openqq restart)" }
|
|
410
|
+
: { kind: "spawn", reason: "人工请求重启(bot 未运行,直接拉起)" }
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
if (action.kind === "ok") return { action: "ok", detail: "健康", killedPid: null, spawnedPid: null }
|
|
414
|
+
if (action.kind === "cooldown") {
|
|
415
|
+
log(`[supervisor] 冷却中(上次重启 ${Math.round((now - (action.untilMs - policy.cooldownMs)) / 1000)}s 前),本轮跳过`)
|
|
416
|
+
return { action: "cooldown", detail: "冷却跳过", killedPid: null, spawnedPid: null }
|
|
417
|
+
}
|
|
418
|
+
if (action.kind === "yield") {
|
|
419
|
+
return { action: "yield", detail: action.reason, killedPid: null, spawnedPid: null }
|
|
420
|
+
}
|
|
421
|
+
if (action.kind === "give-up") {
|
|
422
|
+
const message = `⚠️ QQBot 看门狗已放弃:${action.restarts} 次重启/${Math.round(policy.windowMs / 60_000)} 分钟仍不健康。继续自动重启没有意义(同因反复死亡),请人工检查 %TEMP%\\opencode 下 bot.out.log 与 ~/.openqq/watchdog.log。`
|
|
423
|
+
audit(`give-up:${message}`)
|
|
424
|
+
log(`[supervisor] give-up:${action.restarts} 次重启仍异常,停止循环并上报`)
|
|
425
|
+
// 告警去抖:30 分钟内只报一次(计划任务每 10 分钟一轮,防止轰炸)
|
|
426
|
+
const lastAlert = state.alertedAt ?? 0
|
|
427
|
+
if (now - lastAlert > 30 * 60_000) {
|
|
428
|
+
try {
|
|
429
|
+
deps.alert?.(message)
|
|
430
|
+
state.alertedAt = now
|
|
431
|
+
writeFileSync(statePath, JSON.stringify(state))
|
|
432
|
+
} catch {
|
|
433
|
+
/* 上报失败不阻断 */
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
return { action: "give-up", detail: message, killedPid: null, spawnedPid: null }
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// spawn / grace-kill-spawn
|
|
440
|
+
let killedPid: number | null = null
|
|
441
|
+
if (action.kind === "grace-kill-spawn" && action.killPid !== process.pid) {
|
|
442
|
+
const pid = action.killPid
|
|
443
|
+
// —— 杀前复核(2026-11-09 加固红线):decide 与执行之间 bot 可能刚恢复心跳
|
|
444
|
+
//(事件循环解堵/冷启动落盘延迟),此时直接杀=误杀良民(合法杀掉干活中的 bot)。
|
|
445
|
+
// 复核前先给 bot 的心跳写入一个短暂到达窗口(300ms):读健康度与动刀之间
|
|
446
|
+
// 若有心跳落盘必须被看见;随后重读一次,转新鲜即改判 ok、放弃本轮,全程审计留痕。
|
|
447
|
+
// 心跳「缺失」不豁免(语义同 decide:缺失视为未恢复,维持原判)。——
|
|
448
|
+
// 例外:manual-restart(人工意图即权威,不存在"误杀")。——
|
|
449
|
+
if (deps.request !== "manual-restart") {
|
|
450
|
+
await sleep(300)
|
|
451
|
+
const recheck = readBotHealth(deps.paths, Date.now())
|
|
452
|
+
const recheckFresh =
|
|
453
|
+
recheck.heartbeatAgeMs !== null && recheck.heartbeatAgeMs <= HEARTBEAT_STALE_MS
|
|
454
|
+
if (recheck.pidAlive !== false && recheckFresh) {
|
|
455
|
+
const ageSec = Math.round((recheck.heartbeatAgeMs ?? 0) / 1000)
|
|
456
|
+
audit(`杀前复核改判 ok:pid=${pid} 心跳已恢复(年龄 ${ageSec}s),放弃误杀`)
|
|
457
|
+
log(`[supervisor] 杀前复核改判 ok:心跳已恢复(${ageSec}s),放弃杀 pid=${pid}`)
|
|
458
|
+
return { action: "ok", detail: `杀前复核:心跳已恢复,放弃误杀 pid=${pid}`, killedPid: null, spawnedPid: null }
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
// 升级杀(fleet-guard):TERM → 宽限轮询 → KILL。
|
|
462
|
+
// Windows 上 Node 的 SIGTERM≈立即终止(无 handler 语义),宽限主要服务 posix;
|
|
463
|
+
// 但轮询仍统一:确认死亡后才拉起,绝不「边杀边拉」。
|
|
464
|
+
kill(pid, "SIGTERM")
|
|
465
|
+
const deadline = now + policy.graceMs
|
|
466
|
+
let alive = isAlive(pid)
|
|
467
|
+
while (alive && Date.now() < deadline) {
|
|
468
|
+
await sleep(250)
|
|
469
|
+
alive = isAlive(pid)
|
|
470
|
+
}
|
|
471
|
+
if (alive) {
|
|
472
|
+
kill(pid, "SIGKILL")
|
|
473
|
+
const hardDeadline = Date.now() + 3_000
|
|
474
|
+
while (alive && Date.now() < hardDeadline) {
|
|
475
|
+
await sleep(250)
|
|
476
|
+
alive = isAlive(pid)
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
if (alive) {
|
|
480
|
+
audit(`give-up-kill:pid=${pid} 无法终止(权限/系统级),本次不拉起`)
|
|
481
|
+
return { action: "give-up", detail: `pid=${pid} 无法终止`, killedPid: null, spawnedPid: null }
|
|
482
|
+
}
|
|
483
|
+
killedPid = pid
|
|
484
|
+
}
|
|
485
|
+
// design §3.9.1 监督矩阵行 2「无锁 / 锁 pid 已死 → 清锁 → 拉起」:
|
|
486
|
+
// 死 bot 的锁文件由监督者在拉起前清理。否则刚死(锁 mtime<30s)时
|
|
487
|
+
// 新实例 try 模式判锁新鲜而拒绝接管,本轮拉起空转,须再等一个巡检周期。
|
|
488
|
+
// 仅当锁 pid 已死/无锁才删(grace-kill 路径已确认死亡,killedPid 非空)。
|
|
489
|
+
try {
|
|
490
|
+
if (killedPid !== null || health.lockPid === null || health.pidAlive === false) {
|
|
491
|
+
unlinkSync(deps.paths.lockPath)
|
|
492
|
+
audit(`清锁:${deps.paths.lockPath}(${action.reason})`)
|
|
493
|
+
}
|
|
494
|
+
} catch {
|
|
495
|
+
/* 锁不存在或删除失败:新实例 try 模式仍按 mtime 仲裁,不阻断拉起 */
|
|
496
|
+
}
|
|
497
|
+
const spawnedPid = deps.spawn()
|
|
498
|
+
state.restartLog.push(Date.now())
|
|
499
|
+
state.restartLog = state.restartLog.filter((t) => t > Date.now() - policy.windowMs * 2)
|
|
500
|
+
try {
|
|
501
|
+
writeFileSync(statePath, JSON.stringify(state))
|
|
502
|
+
} catch {
|
|
503
|
+
log("[supervisor] 强度账落盘失败(不影响本次拉起)")
|
|
504
|
+
}
|
|
505
|
+
const detail = `${action.reason};${killedPid ? `已优雅停 pid=${killedPid};` : ""}已拉起 pid=${spawnedPid}`
|
|
506
|
+
// 审计分家(2026-11-09 加固红线):「主动杀」与「验尸拉新」必须在日志里一眼可辨——
|
|
507
|
+
// 历史上两者同文案导致无声死亡无法归因(2026-11-09 他杀排查实证:审计缺陷遮蔽真凶)。
|
|
508
|
+
audit(killedPid ? `主动杀:${detail}` : `验尸拉新:${detail}`)
|
|
509
|
+
return { action: "restart", detail, killedPid, spawnedPid }
|
|
510
|
+
} finally {
|
|
511
|
+
release()
|
|
512
|
+
}
|
|
513
|
+
}
|