@linjz/opencode-qqbot 0.3.16 → 0.3.17
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 +303 -266
- package/README.zh-CN.md +313 -0
- package/dist/notify-cli.js +64 -12
- package/dist/opencode-qqbot-plugin.js +356 -92
- package/dist/openqq-bot.js +878 -226
- package/dist/openqq-cli.js +253 -64
- package/dist/openqq-watchdog.js +373 -110
- package/package.json +2 -2
- package/src/bridge.ts +292 -3
- package/src/cli/notify.ts +4 -1
- package/src/cli/watchdog-main.ts +22 -7
- package/src/commands.ts +36 -10
- package/src/config.ts +39 -5
- package/src/core/bot-config.ts +66 -0
- package/src/core/bot-control.ts +21 -3
- package/src/core/bot-launcher.ts +4 -2
- package/src/core/cron-reminders.ts +84 -0
- package/src/core/discovery.ts +207 -169
- package/src/core/error-rescue.ts +1 -1
- package/src/core/file-log.ts +16 -7
- package/src/core/inflight-journal.ts +1 -0
- package/src/core/instance-lock.ts +32 -1
- package/src/core/log-rotate.ts +91 -0
- package/src/core/mirror.ts +7 -1
- package/src/core/notices.ts +62 -0
- package/src/core/outbound-sanitize.ts +29 -0
- package/src/core/permission.ts +7 -0
- package/src/core/queue-view.ts +1 -0
- package/src/core/send-media.ts +29 -2
- package/src/core/start-error.ts +26 -0
- package/src/core/stt.ts +55 -0
- package/src/core/supervisor-election.ts +53 -0
- package/src/core/watchdog.ts +171 -14
- package/src/index.ts +262 -250
- package/src/opencode/client.ts +32 -1
- package/src/opencode/mirror.ts +10 -3
- package/src/plugin-entry.ts +21 -2
- package/src/qq/gateway.ts +35 -0
- package/src/qq/media.ts +21 -0
- package/src/qq/sender.ts +50 -1
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// @input: 无依赖(纯文本工具)
|
|
2
|
+
// @output: cmdInput/cmdEnter 标签构造、stripInteractionTags 兜底剥离、NOTICE 文案目录
|
|
3
|
+
// @pos: core - 通知文案目录(2026-11-22 学习吸收轮:融合 dsh-qqbot errors.ts/session-notice.ts
|
|
4
|
+
// 目录制之长——用户可见文案单一出口、可测;P0 佐证=QQ 官方文档「文本交互」
|
|
5
|
+
// bot.q.qq.com/wiki api-v2,2026-10-26 更新版,<qqbot-cmd-input>/<qqbot-cmd-enter> 形状确认)
|
|
6
|
+
//
|
|
7
|
+
// ⚠️ 平台边界(官方文档原文):
|
|
8
|
+
// - 指令标签仅在 **markdown 消息** 内生效;纯文本兜底通道会把标签当字面文本显示
|
|
9
|
+
// (尖括号泄漏)—— sender.ts formatForQQ 必须走 stripInteractionTags 兜底(AstrBot#8755 同款坑)。
|
|
10
|
+
// - text/show 均 ≤100 字符且须 urlencode;cmd-enter「群聊和文字子频道不支持该能力」,
|
|
11
|
+
// 故 recover 类提示统一用 cmd-input(插入输入框,用户确认后发送),不替用户自动发指令。
|
|
12
|
+
|
|
13
|
+
/** 参数指令标签:<qqbot-cmd-input>(P0 文本交互,点击=把 text 插入输入框)。 */
|
|
14
|
+
export function cmdInput(text: string, show?: string, reference = false): string {
|
|
15
|
+
const enc = (s: string): string => encodeURIComponent(s)
|
|
16
|
+
const attrs = [`text="${enc(text)}"`]
|
|
17
|
+
if (show !== undefined) attrs.push(`show="${enc(show)}"`)
|
|
18
|
+
if (reference) attrs.push('reference="true"')
|
|
19
|
+
return `<qqbot-cmd-input ${attrs.join(" ")} />`
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** 回车指令标签:<qqbot-cmd-enter>(点击直接发送;官方文档注明群聊/文字子频道不支持——慎用)。 */
|
|
23
|
+
export function cmdEnter(text: string, show?: string): string {
|
|
24
|
+
const enc = (s: string): string => encodeURIComponent(s)
|
|
25
|
+
const attrs = [`text="${enc(text)}"`]
|
|
26
|
+
if (show !== undefined) attrs.push(`show="${enc(show)}"`)
|
|
27
|
+
return `<qqbot-cmd-enter ${attrs.join(" ")} />`
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// 纯文本兜底剥离:把交互标签降级为可读文本(show 优先,其次 text),防尖括号泄漏。
|
|
31
|
+
const INTERACTION_TAG = /<qqbot-(cmd-input|cmd-enter)\b[^>]*\/?>/g
|
|
32
|
+
|
|
33
|
+
function tagFallback(tag: string): string {
|
|
34
|
+
const show = /show="([^"]*)"/.exec(tag)?.[1]
|
|
35
|
+
const text = /text="([^"]*)"/.exec(tag)?.[1]
|
|
36
|
+
const pick = show ?? text
|
|
37
|
+
if (!pick) return ""
|
|
38
|
+
try {
|
|
39
|
+
return decodeURIComponent(pick)
|
|
40
|
+
} catch {
|
|
41
|
+
return pick
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 剥离 markdown 专属交互标签(供纯文本兜底通道调用)。 */
|
|
46
|
+
export function stripInteractionTags(text: string): string {
|
|
47
|
+
return text.replace(INTERACTION_TAG, (m: string) => tagFallback(m))
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 用户可见文案目录(单一出口,改文案只动这里)。
|
|
52
|
+
* 每条说得出:出现场景 / 恢复路径 / 为什么用 cmd-input 而非常量文字。
|
|
53
|
+
*/
|
|
54
|
+
export const NOTICE = {
|
|
55
|
+
/**
|
|
56
|
+
* 僵尸收割 expired(bridge.ts reaper):卡死回合被清理后的可见交代。
|
|
57
|
+
* 恢复路径给可点指令(官方文本交互),用户不用手打 /new。
|
|
58
|
+
*/
|
|
59
|
+
reaperExpired: (): string =>
|
|
60
|
+
"⚠️ 检测到一个卡死的回合(长时间无进展),已自动清理;结果可点下面的指令开新会话重试:\n" +
|
|
61
|
+
cmdInput("/new", "🆕 新会话"),
|
|
62
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// @input: 纯文本(无依赖)
|
|
2
|
+
// @output: stripScaffolding
|
|
3
|
+
// @pos: core - 出站脚手架消毒(2026-11-23 学习吸收 Z 项,源=openclaw outbound/sanitize.ts P0)
|
|
4
|
+
//
|
|
5
|
+
// 背景:模型偶发把内部推理/脚手架块写进正文( thinking/system-reminder 等),
|
|
6
|
+
// QQ 会把原始标签渲染给用户。出站前统一剥离——主路径(formatForQQMarkdown)与
|
|
7
|
+
// 纯文本兜底(formatForQQ)同口径,围栏代码块内容不动(调用方在围栏外逐段应用
|
|
8
|
+
// 或由 sender 在剥标签后再做围栏保护,顺序:消毒 → 围栏保护/转义)。
|
|
9
|
+
|
|
10
|
+
/** 内部脚手架块:成对块先剥(含跨行),再剥残留开/闭标签;
|
|
11
|
+
* deepseek 反引号形态 `think`…`/think` 与 claude 尖括号形态都收。 */
|
|
12
|
+
const BLOCK_PATTERNS: RegExp[] = [
|
|
13
|
+
/<system-reminder\b[^>]*>[\s\S]*?<\/system-reminder>/gi,
|
|
14
|
+
/<previous_response\b[^>]*>[\s\S]*?<\/previous_response>/gi,
|
|
15
|
+
/`think`[\s\S]*?`\/think`/gi,
|
|
16
|
+
/<thinking\b[^>]*>[\s\S]*?<\/thinking>/gi,
|
|
17
|
+
// 残留裸标签(不成对的开/闭)
|
|
18
|
+
/<\s*\/?\s*(?:system-reminder|previous_response)\b[^>]*\/?\s*>/gi,
|
|
19
|
+
/<\s*\/?\s*think(?:ing)?\b[^>]*\/?\s*>/gi,
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
/** 剥离内部运行时脚手架块(幂等;连续空行收敛为一行)。 */
|
|
23
|
+
export function stripScaffolding(text: string): string {
|
|
24
|
+
let result = text
|
|
25
|
+
for (const re of BLOCK_PATTERNS) {
|
|
26
|
+
result = result.replace(re, "")
|
|
27
|
+
}
|
|
28
|
+
return result.replace(/\n{3,}/g, "\n\n")
|
|
29
|
+
}
|
package/src/core/permission.ts
CHANGED
|
@@ -619,6 +619,13 @@ export function formatPermissionPrompt(
|
|
|
619
619
|
lines.push("资源:")
|
|
620
620
|
for (const r of resources) lines.push(` ${truncate(r, 300)}`)
|
|
621
621
|
}
|
|
622
|
+
// W 项(2026-11-22 宿主侧学习):官方文档 permissions 页——always 保存工具提案的
|
|
623
|
+
// pattern(shell=命令前缀等)。卡片上明示「总是允许」将保存什么,owner 点之前知道
|
|
624
|
+
// 豁免范围(request.save 即引擎提案的保存规则,仅 always 决策时生效)。
|
|
625
|
+
if (request.save && request.save.length > 0) {
|
|
626
|
+
const saves = request.save.slice(0, 3).map((s) => truncate(s, 120))
|
|
627
|
+
lines.push(`总是允许将保存:${saves.join(";")}`)
|
|
628
|
+
}
|
|
622
629
|
if (request.message) lines.push(`说明:${truncate(request.message, 300)}`)
|
|
623
630
|
lines.push("")
|
|
624
631
|
lines.push("回复「允许」= 仅本次|「总是」= 保存为项目级白名单(后续同类命令永久放行)|「拒绝」= 驳回(含本会话其他待审)")
|
package/src/core/queue-view.ts
CHANGED
package/src/core/send-media.ts
CHANGED
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
// 安全:路径白名单(默认只允许 QQ 图片缓存目录与 bot 工作目录,QQ_SEND_EXTRA_ROOTS 可扩);
|
|
7
7
|
// 大小上限 20MB(官方单次上传上限,base64 前检查)。
|
|
8
8
|
import { readFileSync, statSync } from "node:fs"
|
|
9
|
-
import { resolve, extname, basename, sep } from "node:path"
|
|
9
|
+
import { resolve, extname, basename, sep, join } from "node:path"
|
|
10
|
+
import { homedir } from "node:os"
|
|
10
11
|
import { imageDir } from "../qq/media.js"
|
|
11
12
|
import { uploadQQMedia, sendQQMediaMessage, MediaFileType } from "../qq/api.js"
|
|
12
13
|
import type { MessageContext } from "../qq/types.js"
|
|
@@ -85,13 +86,39 @@ export interface SendLocalFileDeps {
|
|
|
85
86
|
getToken: () => Promise<string>
|
|
86
87
|
}
|
|
87
88
|
|
|
89
|
+
/**
|
|
90
|
+
* 本地路径规范化(X 项,2026-11-22 学习吸收 openclaw local-file-router P0):
|
|
91
|
+
* file:// 前缀剥离(含 Windows file:///C:/ 三斜杠形态)→ URL decode(非法编码按原样)
|
|
92
|
+
* → ~ 展开为家目录。白名单/拒绝名单判定必须先于或基于规范化结果,否则同一文件
|
|
93
|
+
* 因写法不同得到两种判定。
|
|
94
|
+
*/
|
|
95
|
+
export function normalizeLocalPath(p: string): string {
|
|
96
|
+
let r = p.trim()
|
|
97
|
+
if (r.startsWith("file://")) {
|
|
98
|
+
r = r.slice("file://".length)
|
|
99
|
+
if (/^\/[a-zA-Z]:[\\/]/.test(r)) r = r.slice(1)
|
|
100
|
+
}
|
|
101
|
+
try {
|
|
102
|
+
r = decodeURIComponent(r)
|
|
103
|
+
} catch {
|
|
104
|
+
/* 非法 % 编码按原样,后续 stat 会给出「不存在」的准确交代 */
|
|
105
|
+
}
|
|
106
|
+
if (r === "~" || r.startsWith("~/") || r.startsWith("~\\")) {
|
|
107
|
+
r = join(homedir(), r.slice(1))
|
|
108
|
+
}
|
|
109
|
+
return r
|
|
110
|
+
}
|
|
111
|
+
|
|
88
112
|
/** 白名单校验 → 读取 → 上传 → 发送媒体消息;错误以中文短语抛出(调用方回显用户)。 */
|
|
89
113
|
export async function sendLocalFile(
|
|
90
114
|
ctx: MessageContext,
|
|
91
115
|
filePath: string,
|
|
92
116
|
deps: SendLocalFileDeps,
|
|
93
117
|
): Promise<string> {
|
|
94
|
-
|
|
118
|
+
// X 项(2026-11-22 学习吸收,源=openclaw local-file-router P0):路径规范化先行——
|
|
119
|
+
// file:// 前缀剥离、URL decode、~ 展开;规范化在拒绝名单/白名单之前(否则
|
|
120
|
+
// file:///C:/x 与 C:/x 同一文件两种判定结果)。非法编码按原样不炸。
|
|
121
|
+
const trimmed = normalizeLocalPath(filePath)
|
|
95
122
|
// DEF-qqbot-20261112-03:文件级拒绝优先于目录白名单(穿越解析落白名单根也拦)
|
|
96
123
|
if (isDeniedSendFile(trimmed)) {
|
|
97
124
|
throw new Error("该文件属于密钥/凭据类,禁止外发(已拦截)")
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// @input: node:util
|
|
2
|
+
// @output: formatStartupError, startupDiagnosticBundle
|
|
3
|
+
// @pos: core - 启动失败可观测性(DEF-20261120-01a)
|
|
4
|
+
//
|
|
5
|
+
// 2026-11-20 事故实证:bot 拉起通道 8ms 速死,日志只有「启动失败: {}」——
|
|
6
|
+
// 抛出值是非 Error 对象时被 console 序列化成空对象,根因整个丢失,僵尸锁
|
|
7
|
+
// 自激 + 看门狗 give-up,引擎恢复后仍长期离线。本模块保证:
|
|
8
|
+
// ① 任何抛出值(Error / 字符串 / 任意对象)都以可读形态落日志;
|
|
9
|
+
// ② 附一次性环境诊断包(cwd/运行时/argv/env 键清单)——拉起通道与手工
|
|
10
|
+
// 环境的 delta 下次自报家门,不用远程二分。
|
|
11
|
+
import { inspect } from "util"
|
|
12
|
+
|
|
13
|
+
export function formatStartupError(error: unknown): string {
|
|
14
|
+
if (error instanceof Error) return error.stack ?? error.message
|
|
15
|
+
if (typeof error === "string") return error
|
|
16
|
+
return inspect(error, { depth: 6, colors: false, maxArrayLength: 50, maxStringLength: 500 })
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function startupDiagnosticBundle(): string {
|
|
20
|
+
return JSON.stringify({
|
|
21
|
+
cwd: process.cwd(),
|
|
22
|
+
execPath: process.execPath,
|
|
23
|
+
argv: process.argv.slice(2),
|
|
24
|
+
envKeys: Object.keys(process.env).sort(),
|
|
25
|
+
})
|
|
26
|
+
}
|
package/src/core/stt.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// @input: 音频字节 + OpenAI 兼容 STT 端点配置(fetch 可注入,测试用)
|
|
2
|
+
// @output: sttConfigured / sttTranscribe
|
|
3
|
+
// @pos: core - 语音外部转写回退(2026-11-23 学习吸收 AD 项,源=hermes-agent adapter.py P0 邻接)
|
|
4
|
+
//
|
|
5
|
+
// 链路:QQ 内置 ASR(asr_refer_text,免费优先)→ 空时回退本模块(GLM-ASR/Whisper/
|
|
6
|
+
// 任意 OpenAI 兼容 /audio/transcriptions 端点)。未配置三键时本模块整体离线——
|
|
7
|
+
// 语音消息走既有「不支持」路径,行为零变化。密钥只经 env 读取,绝不落盘/回显。
|
|
8
|
+
|
|
9
|
+
export interface SttConfig {
|
|
10
|
+
baseUrl: string
|
|
11
|
+
apiKey: string
|
|
12
|
+
model: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** 从 env 读 STT 配置;缺任一必需项返回 null(=外部回退离线)。 */
|
|
16
|
+
export function sttConfigured(env: NodeJS.ProcessEnv = process.env): SttConfig | null {
|
|
17
|
+
const baseUrl = (env.QQ_STT_BASE_URL ?? "").trim().replace(/\/+$/, "")
|
|
18
|
+
const apiKey = (env.QQ_STT_API_KEY ?? "").trim()
|
|
19
|
+
const model = (env.QQ_STT_MODEL ?? "whisper-1").trim()
|
|
20
|
+
if (!baseUrl || !apiKey) return null
|
|
21
|
+
return { baseUrl, apiKey, model }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 调 OpenAI 兼容转写端点。失败抛错(调用方转有据短语);fetchImpl 可注入。
|
|
26
|
+
* multipart:file + model;30s 超时。
|
|
27
|
+
*/
|
|
28
|
+
export async function sttTranscribe(
|
|
29
|
+
bytes: Uint8Array,
|
|
30
|
+
filename: string,
|
|
31
|
+
cfg: SttConfig,
|
|
32
|
+
fetchImpl: typeof fetch = fetch,
|
|
33
|
+
): Promise<string> {
|
|
34
|
+
const form = new FormData()
|
|
35
|
+
form.append("model", cfg.model)
|
|
36
|
+
form.append("file", new Blob([bytes.buffer as ArrayBuffer]), filename)
|
|
37
|
+
const ctrl = new AbortController()
|
|
38
|
+
const timer = setTimeout(() => ctrl.abort(), 30_000)
|
|
39
|
+
let res: Response
|
|
40
|
+
try {
|
|
41
|
+
res = await fetchImpl(`${cfg.baseUrl}/audio/transcriptions`, {
|
|
42
|
+
method: "POST",
|
|
43
|
+
headers: { Authorization: `Bearer ${cfg.apiKey}` },
|
|
44
|
+
body: form,
|
|
45
|
+
signal: ctrl.signal,
|
|
46
|
+
})
|
|
47
|
+
} finally {
|
|
48
|
+
clearTimeout(timer)
|
|
49
|
+
}
|
|
50
|
+
if (!res.ok) throw new Error(`STT ${res.status}`)
|
|
51
|
+
const j = (await res.json()) as { text?: string }
|
|
52
|
+
const text = (j.text ?? "").trim()
|
|
53
|
+
if (!text) throw new Error("STT 空转写")
|
|
54
|
+
return text
|
|
55
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// @input: fs、时钟
|
|
2
|
+
// @output: electSupervisor(channel, opts?)
|
|
3
|
+
// @pos: core - 监督通道选主租约(2026-11-20 owner 批「双触发器归一」)
|
|
4
|
+
//
|
|
5
|
+
// 背景:superviseOnce 的监督矩阵已是杀/拉唯一权威,但触发器有两个——
|
|
6
|
+
// service(计划任务 openqq-watchdog --once)与 plugin(引擎内嵌引导器巡检)。
|
|
7
|
+
// 双触发器相位不一,监督者认领互斥(90s claim)只能逐 tick 串行,历史上造成
|
|
8
|
+
// 排程撞车(11-20 激活亲历 restart 与巡检互相踩相位)。
|
|
9
|
+
// 归一:本租约选出一个独占监督通道——赢家每 tick 续租并照常 superviseOnce,
|
|
10
|
+
// 输家整轮让贤(连 superviseOnce 都不进:不抢认领、不写强度账、零干扰);
|
|
11
|
+
// 租约过期(赢家死亡/停排,TTL 10 分钟)后另一通道自动接管,双向自愈。
|
|
12
|
+
// 同通道不同 pid(多引擎并发加载插件)同样互斥。
|
|
13
|
+
// fail-open:租约文件不可写时放行监督——监督缺失比双触发更糟。
|
|
14
|
+
import { readFileSync, writeFileSync } from "fs"
|
|
15
|
+
import { join } from "path"
|
|
16
|
+
import { homedir } from "os"
|
|
17
|
+
|
|
18
|
+
export type SupervisorChannel = "service" | "plugin"
|
|
19
|
+
|
|
20
|
+
export interface SupervisorLease {
|
|
21
|
+
channel: SupervisorChannel
|
|
22
|
+
pid: number
|
|
23
|
+
until: number
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const LEASE_PATH = join(homedir(), ".openqq", "supervisor-lease.json")
|
|
27
|
+
const LEASE_TTL_MS = 10 * 60_000
|
|
28
|
+
|
|
29
|
+
/** 选主:持有/夺得租约返回 true(可监督);他通道(或他 pid)持新鲜租约返回 false(让贤)。 */
|
|
30
|
+
export function electSupervisor(
|
|
31
|
+
channel: SupervisorChannel,
|
|
32
|
+
opts?: { ttlMs?: number; now?: number; path?: string },
|
|
33
|
+
): boolean {
|
|
34
|
+
const ttlMs = opts?.ttlMs ?? LEASE_TTL_MS
|
|
35
|
+
const now = opts?.now ?? Date.now()
|
|
36
|
+
const path = opts?.path ?? LEASE_PATH
|
|
37
|
+
try {
|
|
38
|
+
let cur: Partial<SupervisorLease> | null = null
|
|
39
|
+
try {
|
|
40
|
+
cur = JSON.parse(readFileSync(path, "utf-8")) as Partial<SupervisorLease>
|
|
41
|
+
} catch {
|
|
42
|
+
/* 无租约或损坏 → 视为可夺 */
|
|
43
|
+
}
|
|
44
|
+
if (cur && typeof cur.until === "number" && cur.until > now) {
|
|
45
|
+
const mine = cur.channel === channel && cur.pid === process.pid
|
|
46
|
+
if (!mine) return false
|
|
47
|
+
}
|
|
48
|
+
writeFileSync(path, JSON.stringify({ channel, pid: process.pid, until: now + ttlMs }))
|
|
49
|
+
return true
|
|
50
|
+
} catch {
|
|
51
|
+
return true // fail-open:租约不可写不阻断监督
|
|
52
|
+
}
|
|
53
|
+
}
|
package/src/core/watchdog.ts
CHANGED
|
@@ -7,9 +7,11 @@
|
|
|
7
7
|
// 锁文件 pid(单实例仲裁的唯一真相)+ process.kill(pid,0) + 心跳文件新鲜度。
|
|
8
8
|
// 约定:锁 mtime 由 bot 每 10s 刷新(instance-lock);心跳文件由 bot 每 60s 刷新,
|
|
9
9
|
// 且 2026-11-09 起「抢锁后立即写」,因此「进程活但心跳陈旧」= 真僵死,不是启动中。
|
|
10
|
-
import { readFileSync, statSync, unlinkSync, writeFileSync } from "fs"
|
|
11
|
-
import { join } from "path"
|
|
10
|
+
import { existsSync, readFileSync, statSync, unlinkSync, writeFileSync } from "fs"
|
|
11
|
+
import { dirname, join } from "path"
|
|
12
12
|
import { homedir } from "os"
|
|
13
|
+
import { enforceLogBudget, logLimitsFromEnv, rotateLogIfNeeded } from "./log-rotate.js"
|
|
14
|
+
import { releaseLocksOfPid } from "./instance-lock.js"
|
|
13
15
|
|
|
14
16
|
/** 心跳超过 5 分钟未刷新 = 事件循环僵死(与既有看门狗阈值一致) */
|
|
15
17
|
export const HEARTBEAT_STALE_MS = 5 * 60_000
|
|
@@ -202,16 +204,80 @@ export function readEnvField(envPath: string, key: string): string | null {
|
|
|
202
204
|
}
|
|
203
205
|
}
|
|
204
206
|
|
|
205
|
-
/**
|
|
207
|
+
/** bot 是否失能(无锁 / 持锁进程已死)——选主让贤的破格判据:bot 失能时任何通道都不许礼貌让贤。 */
|
|
208
|
+
export function isBotDown(health: BotHealth): boolean {
|
|
209
|
+
return health.lockPid === null || health.pidAlive === false
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** 追加一行巡检日志到统一日志 ~/.openqq/openqq.log(数据目录,不是代码;
|
|
213
|
+
* 2026-11-20 合并批:bot 与看门狗同文件,一眼归因全链路) */
|
|
206
214
|
export function appendWatchdogLog(line: string): void {
|
|
207
215
|
try {
|
|
208
|
-
const
|
|
209
|
-
|
|
216
|
+
const logPath = join(homedir(), ".openqq", "openqq.log")
|
|
217
|
+
const limits = logLimitsFromEnv()
|
|
218
|
+
if (existsSync(logPath) && statSync(logPath).size > limits.maxBytes) {
|
|
219
|
+
if (rotateLogIfNeeded(logPath, limits)) enforceLogBudget(logPath, limits)
|
|
220
|
+
}
|
|
221
|
+
writeFileSync(logPath, `${new Date().toISOString()} ${line}\n`, { flag: "a" })
|
|
210
222
|
} catch {
|
|
211
223
|
/* 日志失败不阻断巡检 */
|
|
212
224
|
}
|
|
213
225
|
}
|
|
214
226
|
|
|
227
|
+
/**
|
|
228
|
+
* 诛杀审计日志(DEF-20261120 墙 owner 当轮令「决策可审计」):独立文件 ~/.openqq/kills.log。
|
|
229
|
+
*
|
|
230
|
+
* 设计判据(审计三问)——每条诛杀记录必须可回答:
|
|
231
|
+
* ①判据是什么(为何判死:心跳陈旧 N 分钟/锁死/进程退出,附当时健康度快照)
|
|
232
|
+
* ②动作是什么(杀谁:pid;怎么杀:TERM→KILL 升级链;结果:确认死亡/无法终止)
|
|
233
|
+
* ③后果是什么(拉起了谁:新 pid;强度账现状:窗口内第几次)
|
|
234
|
+
*
|
|
235
|
+
* 与统一日志(openqq.log)的分工:openqq.log=全链路时间线(bot 输出+巡检混排,事后按时间归因);
|
|
236
|
+
* kills.log=诛杀决策专线(只有杀戮级动作,事后审计免捞沙)。两处都写不冗余——
|
|
237
|
+
* 审计场景下 openqq.log 会被 bot 高频输出冲刷稀释(11-20 实证:30 分钟卡死现场被
|
|
238
|
+
* 后续日志淹没,诛杀归因只能靠 supervisor 片段倒推),kills.log 保证决策记录永不被稀释。
|
|
239
|
+
*/
|
|
240
|
+
export function appendKillLog(entry: KillAuditEntry, logPath = join(homedir(), ".openqq", "kills.log")): void {
|
|
241
|
+
try {
|
|
242
|
+
// 单行 JSONL:机器可解析(工具审计)+人类可读(字段名自释)。
|
|
243
|
+
// 轮转归 log-rotate 统一管辖(与 openqq.log 同口径 20MB×4 代/100MB 总预算;
|
|
244
|
+
// 量级=决策级事件每天数条,statSync 每次诛杀一次可忽略)。
|
|
245
|
+
writeFileSync(logPath, `${JSON.stringify(entry)}\n`, { flag: "a" })
|
|
246
|
+
const limits = logLimitsFromEnv()
|
|
247
|
+
if (existsSync(logPath) && statSync(logPath).size > limits.maxBytes) {
|
|
248
|
+
if (rotateLogIfNeeded(logPath, limits)) enforceLogBudget(logPath, limits)
|
|
249
|
+
}
|
|
250
|
+
} catch {
|
|
251
|
+
/* 审计日志失败不阻断监督主流程——监督本身即最后防线 */
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** 诛杀审计记录(字段=审计三问的机器形态;@ts 这里的时间一律 epoch ms) */
|
|
256
|
+
export interface KillAuditEntry {
|
|
257
|
+
/** 记录类型:decision=完整决策审计;liveness-check=拉起后存活确认 */
|
|
258
|
+
kind: "decision" | "liveness-check"
|
|
259
|
+
/** ①判据:触发动作的原始原因(如「心跳陈旧 30 分钟」) */
|
|
260
|
+
reason: string
|
|
261
|
+
/** ①判据附证:动刀时刻的健康度快照(判死依据的原始数据,审计不复算) */
|
|
262
|
+
health: {
|
|
263
|
+
lockPid: number | null
|
|
264
|
+
pidAlive: boolean | null
|
|
265
|
+
heartbeatAgeMs: number | null
|
|
266
|
+
lockAgeMs: number | null
|
|
267
|
+
}
|
|
268
|
+
/** ②动作:杀掉的 pid(null=本次为纯拉起/复核类记录) */
|
|
269
|
+
killedPid: number | null
|
|
270
|
+
/** ②动作:升级链终点(TERM 快速退出 / KILL 强杀 / 无法终止) */
|
|
271
|
+
killEscalation: "TERM" | "KILL" | "unterminated" | "n/a"
|
|
272
|
+
/** ③后果:拉起的新 pid */
|
|
273
|
+
spawnedPid: number | null
|
|
274
|
+
/** ③后果:强度账(窗口内重启次数/上限) */
|
|
275
|
+
restartIntensity: string
|
|
276
|
+
/** ③后果:拉起后存活复核结论(liveness-check 专用;decision 记录取证时为 null) */
|
|
277
|
+
livenessVerdict: string | null
|
|
278
|
+
at: number
|
|
279
|
+
}
|
|
280
|
+
|
|
215
281
|
// ===== 监督层(2026-11-09 重构,替代裸 healOnce 的「无脑杀旧拉新」)=====
|
|
216
282
|
// 设计对标(当日检索实证):
|
|
217
283
|
// - Erlang OTP supervisor:maximum restart intensity——窗口内重启超限 → 放弃并上报,
|
|
@@ -310,6 +376,12 @@ export interface SuperviseDeps {
|
|
|
310
376
|
claimPath?: string
|
|
311
377
|
/** 监督动作审计日志路径(测试注入临时文件,避免污染真实 watchdog.log) */
|
|
312
378
|
auditLogPath?: string
|
|
379
|
+
/**
|
|
380
|
+
* 拉起后存活确认(DEF-20261120 墙二次追击层)注入点:
|
|
381
|
+
* 缺省=生产行为(10s 后复核进程+锁,失败二次拉起);测试注入 false=整层跳过
|
|
382
|
+
*(fake spawn 返回假 pid、锁不落盘,生产复核在测试环境必判死,旧用例语义不变)。
|
|
383
|
+
*/
|
|
384
|
+
livenessCheck?: boolean
|
|
313
385
|
}
|
|
314
386
|
|
|
315
387
|
export interface SuperviseResult {
|
|
@@ -419,9 +491,9 @@ export async function superviseOnce(deps: SuperviseDeps): Promise<SuperviseResul
|
|
|
419
491
|
return { action: "yield", detail: action.reason, killedPid: null, spawnedPid: null }
|
|
420
492
|
}
|
|
421
493
|
if (action.kind === "give-up") {
|
|
422
|
-
const message = `⚠️ QQBot
|
|
494
|
+
const message = `⚠️ QQBot 看门狗已达重启强度上限:${action.restarts} 次/${Math.round(policy.windowMs / 60_000)} 分钟仍不健康(同因反复死亡)。降频重试继续——巡检不会停,强度窗口滑动后自动恢复,引擎/环境自愈即自行好转;若持续收到此告警,请检查 ~/.openqq/openqq.log(bot 与看门狗统一日志)。`
|
|
423
495
|
audit(`give-up:${message}`)
|
|
424
|
-
log(`[supervisor] give-up:${action.restarts}
|
|
496
|
+
log(`[supervisor] give-up:${action.restarts} 次重启仍异常,降频重试继续并上报(不再永动猛拉)`)
|
|
425
497
|
// 告警去抖:30 分钟内只报一次(计划任务每 10 分钟一轮,防止轰炸)
|
|
426
498
|
const lastAlert = state.alertedAt ?? 0
|
|
427
499
|
if (now - lastAlert > 30 * 60_000) {
|
|
@@ -485,14 +557,30 @@ export async function superviseOnce(deps: SuperviseDeps): Promise<SuperviseResul
|
|
|
485
557
|
// design §3.9.1 监督矩阵行 2「无锁 / 锁 pid 已死 → 清锁 → 拉起」:
|
|
486
558
|
// 死 bot 的锁文件由监督者在拉起前清理。否则刚死(锁 mtime<30s)时
|
|
487
559
|
// 新实例 try 模式判锁新鲜而拒绝接管,本轮拉起空转,须再等一个巡检周期。
|
|
488
|
-
//
|
|
560
|
+
// 甲乙统一(2026-11-20 owner 批「修甲乙」):单进程多角色持多把锁——
|
|
561
|
+
// 杀进程即按 pid 清扫其持有的全部实例锁(锁即进程,调用方不再记角色名单;
|
|
562
|
+
// 多角色改造前只清单把,残留锁曾把 restart 的新实例弹飞——ceshi 僵尸锁
|
|
563
|
+
// 挡道 11-20 激活亲历)。已知锁路径兜底直删,兼容非 openqq-* 命名与
|
|
564
|
+
// pid 读不到的边角。
|
|
489
565
|
try {
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
566
|
+
const locksDir = dirname(deps.paths.lockPath)
|
|
567
|
+
let cleared: string[] = []
|
|
568
|
+
if (killedPid !== null) {
|
|
569
|
+
cleared = releaseLocksOfPid(killedPid, locksDir)
|
|
570
|
+
} else if (health.pidAlive === false && health.lockPid !== null) {
|
|
571
|
+
cleared = releaseLocksOfPid(health.lockPid, locksDir)
|
|
572
|
+
}
|
|
573
|
+
if (existsSync(deps.paths.lockPath)) {
|
|
574
|
+
try {
|
|
575
|
+
unlinkSync(deps.paths.lockPath)
|
|
576
|
+
if (!cleared.includes(deps.paths.lockPath)) cleared.push(deps.paths.lockPath)
|
|
577
|
+
} catch {
|
|
578
|
+
/* 锁不存在或删除失败:新实例 try 模式仍按 mtime 仲裁,不阻断拉起 */
|
|
579
|
+
}
|
|
493
580
|
}
|
|
581
|
+
if (cleared.length > 0) audit(`清锁:${cleared.join("、")}(${action.reason})`)
|
|
494
582
|
} catch {
|
|
495
|
-
/*
|
|
583
|
+
/* 清锁失败不阻断拉起 */
|
|
496
584
|
}
|
|
497
585
|
const spawnedPid = deps.spawn()
|
|
498
586
|
state.restartLog.push(Date.now())
|
|
@@ -502,11 +590,80 @@ export async function superviseOnce(deps: SuperviseDeps): Promise<SuperviseResul
|
|
|
502
590
|
} catch {
|
|
503
591
|
log("[supervisor] 强度账落盘失败(不影响本次拉起)")
|
|
504
592
|
}
|
|
505
|
-
|
|
593
|
+
|
|
594
|
+
// ===== 拉起后存活确认(DEF-20261120 墙二次追击层)=====
|
|
595
|
+
// 背景(2026-11-20 修订时更正注记):立项时引用的「11-20 15:17 主杀后拉起 7001
|
|
596
|
+
// 秒死」实系 lock-sweep 测试泄漏的假审计行(假 pid 7001,已在测试补 auditLogPath
|
|
597
|
+
// 隔离后根治)——该时刻真实 bot 存活。本层保留立项,因为「拉起后秒死」这一失败类
|
|
598
|
+
// 当日真实存在(早晨 8ms 速死群,根因未钉、仪器已埋):监督者要等下轮巡检
|
|
599
|
+
//(计划任务 3min/常驻 10min)才能再拉,期间 bot 继续失能;若死因未消(dist
|
|
600
|
+
// 混合态等),将进入「杀-拉-死-等-杀」的慢循环,每轮空转一个巡检周期直至 give-up。
|
|
601
|
+
// 修复:拉起后立即做 10s 存活确认(进程在 + 锁建立),失败=立刻二次拉起(仅一次,
|
|
602
|
+
// 防递归爆炸——二次拉起交由下轮巡检接力,与强度账协同防永动)。
|
|
603
|
+
// 强度账语义不变:本函数每进场只记 1 次重启(上方 restartLog.push),存活确认
|
|
604
|
+
// 的二次拉起不另记账——它是「本次重启的完整性收尾」而非新重启。
|
|
605
|
+
// 测试注入:livenessCheck=false 跳过整层(fake 环境判死恒真)。
|
|
606
|
+
let livenessVerdict = "alive"
|
|
607
|
+
let respawnPid: number | null = null
|
|
608
|
+
if (deps.livenessCheck !== false) {
|
|
609
|
+
const graceWaitMs = 10_000
|
|
610
|
+
await sleep(graceWaitMs)
|
|
611
|
+
const liveness = readBotHealth(deps.paths, Date.now())
|
|
612
|
+
if (!isPidAlive(spawnedPid) || liveness.lockPid === null) {
|
|
613
|
+
// 拉起失败两种形态:进程即死(spawn 竞态/依赖缺失)或进程在但 10s 内锁未建立
|
|
614
|
+
//(启动路径卡死——等价于「生而无魂」)。先清残留锁再二次拉起,防 try 锁挡道。
|
|
615
|
+
livenessVerdict = `dead-after-spawn(10s 复核:进程${isPidAlive(spawnedPid) ? "在但锁未建立" : "已退出"})`
|
|
616
|
+
audit(`二次追击:拉起 pid=${spawnedPid} 失败(${livenessVerdict}),立即重拉`)
|
|
617
|
+
try {
|
|
618
|
+
const locksDir2 = dirname(deps.paths.lockPath)
|
|
619
|
+
let cleared2: string[] = []
|
|
620
|
+
if (!isPidAlive(spawnedPid) && existsSync(deps.paths.lockPath)) {
|
|
621
|
+
cleared2 = releaseLocksOfPid(spawnedPid, locksDir2)
|
|
622
|
+
}
|
|
623
|
+
if (existsSync(deps.paths.lockPath)) {
|
|
624
|
+
try {
|
|
625
|
+
unlinkSync(deps.paths.lockPath)
|
|
626
|
+
if (!cleared2.includes(deps.paths.lockPath)) cleared2.push(deps.paths.lockPath)
|
|
627
|
+
} catch { /* mtime 仲裁兜底 */ }
|
|
628
|
+
}
|
|
629
|
+
if (cleared2.length > 0) audit(`清锁:${cleared2.join("、")}(二次追击前清场)`)
|
|
630
|
+
} catch { /* 清锁失败不阻断二次拉起 */ }
|
|
631
|
+
respawnPid = deps.spawn()
|
|
632
|
+
// 二次拉起同样确认(但不再追击——三次交下轮巡检,防递归)
|
|
633
|
+
await sleep(graceWaitMs)
|
|
634
|
+
const liveness2 = readBotHealth(deps.paths, Date.now())
|
|
635
|
+
if (!isPidAlive(respawnPid) || liveness2.lockPid === null) {
|
|
636
|
+
livenessVerdict += `;二次拉起 pid=${respawnPid} 仍失败——交下轮巡检接力(强度账 ${state.restartLog.length}/${policy.maxRestarts})`
|
|
637
|
+
} else {
|
|
638
|
+
livenessVerdict += `;二次拉起 pid=${respawnPid} 成功`
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
// 诛杀审计(决策可审计三问全要素):杀戮级动作落 kills.log 专线
|
|
643
|
+
if (killedPid !== null || livenessVerdict !== "alive") {
|
|
644
|
+
appendKillLog({
|
|
645
|
+
kind: "decision",
|
|
646
|
+
reason: action.reason,
|
|
647
|
+
health: {
|
|
648
|
+
lockPid: health.lockPid,
|
|
649
|
+
pidAlive: health.pidAlive,
|
|
650
|
+
heartbeatAgeMs: health.heartbeatAgeMs,
|
|
651
|
+
lockAgeMs: health.lockAgeMs,
|
|
652
|
+
},
|
|
653
|
+
killedPid,
|
|
654
|
+
killEscalation: killedPid !== null ? "TERM" : "n/a",
|
|
655
|
+
spawnedPid: respawnPid ?? spawnedPid,
|
|
656
|
+
restartIntensity: `${state.restartLog.length}/${policy.maxRestarts}`,
|
|
657
|
+
livenessVerdict: livenessVerdict !== "alive" ? livenessVerdict : "alive",
|
|
658
|
+
at: Date.now(),
|
|
659
|
+
})
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
const detail = `${action.reason};${killedPid ? `已优雅停 pid=${killedPid};` : ""}已拉起 pid=${respawnPid ?? spawnedPid}${livenessVerdict !== "alive" ? `;${livenessVerdict}` : ""}`
|
|
506
663
|
// 审计分家(2026-11-09 加固红线):「主动杀」与「验尸拉新」必须在日志里一眼可辨——
|
|
507
664
|
// 历史上两者同文案导致无声死亡无法归因(2026-11-09 他杀排查实证:审计缺陷遮蔽真凶)。
|
|
508
665
|
audit(killedPid ? `主动杀:${detail}` : `验尸拉新:${detail}`)
|
|
509
|
-
return { action: "restart", detail, killedPid, spawnedPid }
|
|
666
|
+
return { action: "restart", detail, killedPid, spawnedPid: respawnPid ?? spawnedPid }
|
|
510
667
|
} finally {
|
|
511
668
|
release()
|
|
512
669
|
}
|