@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
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
// @input: 平台(process.platform)、运行时命令、看门狗产物路径
|
|
2
|
+
// @output: build* 纯函数 + serviceInstall/serviceUninstall/serviceStatus
|
|
3
|
+
// @pos: cli - 自启注册器(全平台唯一的 OS 差异点,代码仍是 TS)
|
|
4
|
+
//
|
|
5
|
+
// 2026-11-09 架构红线:平台差异只允许出现在「注册自启项」这一处。
|
|
6
|
+
// 本文件生成三平台的注册配置;不引入 .ps1/.vbs/.bat 作为运行时代码。
|
|
7
|
+
import { spawnSync } from "child_process"
|
|
8
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "fs"
|
|
9
|
+
import { homedir, tmpdir } from "os"
|
|
10
|
+
import { join } from "path"
|
|
11
|
+
|
|
12
|
+
export const WIN_TASK_NAME = "OpenQQBotWatchdog"
|
|
13
|
+
export const SYSTEMD_UNIT = "openqq-watchdog"
|
|
14
|
+
export const LAUNCHD_LABEL = "com.linjp.opencode-qqbot.watchdog"
|
|
15
|
+
|
|
16
|
+
export interface ServiceSpec {
|
|
17
|
+
/** 运行时可执行文件(bun 或 node 的绝对路径) */
|
|
18
|
+
runtimeCmd: string
|
|
19
|
+
/** dist/openqq-watchdog.js 绝对路径 */
|
|
20
|
+
scriptPath: string
|
|
21
|
+
intervalMin: number
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface CommandResult {
|
|
25
|
+
ok: boolean
|
|
26
|
+
detail: string
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function run(cmd: string, args: string[]): CommandResult {
|
|
30
|
+
try {
|
|
31
|
+
// windowsHide:CLI 巡检/注册时不弹控制台窗口(2026-11-09 用户反馈“时不时闪一下”)
|
|
32
|
+
const r = spawnSync(cmd, args, { encoding: "utf-8", windowsHide: true })
|
|
33
|
+
const detail = `${cmd} ${args.join(" ")}\n${(r.stdout ?? "").trim()}${(r.stderr ?? "").trim() ? `\n${r.stderr.trim()}` : ""}`
|
|
34
|
+
return { ok: r.status === 0, detail }
|
|
35
|
+
} catch (error) {
|
|
36
|
+
return { ok: false, detail: `执行失败:${error instanceof Error ? error.message : String(error)}` }
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// ---------- 纯函数(导出供测试) ----------
|
|
41
|
+
|
|
42
|
+
const escXml = (s: string): string =>
|
|
43
|
+
s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """)
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Windows 任务 XML(S4U 注册,2026-11-09 静默拉起缺陷③):
|
|
47
|
+
* schtasks 直调 console 程序在 Interactive 登录型下每次 tick 闪现控制台窗口
|
|
48
|
+
* (Win11 默认终端宿主=Windows Terminal)。S4U=非交互会话,进程零窗口、免存密码。
|
|
49
|
+
* 纯函数生成,注册动作不经任何 shell 中转。
|
|
50
|
+
*/
|
|
51
|
+
export function buildSchtasksTaskXml(spec: ServiceSpec, now = new Date()):
|
|
52
|
+
string {
|
|
53
|
+
const user = escXml(process.env.USERNAME ?? "SYSTEM")
|
|
54
|
+
const trigger =
|
|
55
|
+
`<TimeTrigger><StartBoundary>${now.toISOString()}</StartBoundary>` +
|
|
56
|
+
`<Repetition><Interval>PT${spec.intervalMin}M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition>` +
|
|
57
|
+
`<Enabled>true</Enabled></TimeTrigger>`
|
|
58
|
+
return [
|
|
59
|
+
'<?xml version="1.0" encoding="UTF-16"?>',
|
|
60
|
+
'<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',
|
|
61
|
+
`<RegistrationInfo><Author>${user}</Author><Description>OpenCode QQBot watchdog (plugin-managed, silent)</Description></RegistrationInfo>`,
|
|
62
|
+
`<Triggers>${trigger}</Triggers>`,
|
|
63
|
+
'<Principals><Principal id="Author">' +
|
|
64
|
+
`<UserId>${user}</UserId><LogonType>S4U</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>`,
|
|
65
|
+
"<Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>" +
|
|
66
|
+
"<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>" +
|
|
67
|
+
"<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>" +
|
|
68
|
+
"<ExecutionTimeLimit>PT5M</ExecutionTimeLimit><StartWhenAvailable>true</StartWhenAvailable>" +
|
|
69
|
+
"<Enabled>true</Enabled></Settings>",
|
|
70
|
+
'<Actions Context="Author"><Exec>' +
|
|
71
|
+
`<Command>${escXml(spec.runtimeCmd)}</Command>` +
|
|
72
|
+
`<Arguments>${escXml(`"${spec.scriptPath}" --once`)}</Arguments>` +
|
|
73
|
+
'</Exec></Actions>',
|
|
74
|
+
"</Task>",
|
|
75
|
+
"",
|
|
76
|
+
].join("\n")
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function buildSchtasksXmlArgs(xmlPath: string): string[] {
|
|
80
|
+
return ["/Create", "/TN", WIN_TASK_NAME, "/XML", xmlPath, "/F"]
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** conhost.exe 全路径(Windows 自带;不存在作 fallback 判定) */
|
|
84
|
+
export function conhostPath(platform = process.platform): string | null {
|
|
85
|
+
if (platform !== "win32") return null
|
|
86
|
+
const p = join(process.env.SystemRoot ?? "C:\\Windows", "System32", "conhost.exe")
|
|
87
|
+
try {
|
|
88
|
+
return statSync(p).isFile() ? p : null
|
|
89
|
+
} catch {
|
|
90
|
+
return null
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* 第二梯队:conhost --headless 包装(实测零闪窗、非 shell、无需提权)。
|
|
96
|
+
* 适用未提权进程注册 S4U 被 Access denied 的场景;需用户已登录(Interactive 会话)。
|
|
97
|
+
* 仅在「自启注册」这一处使用(平台差异收口红线)。
|
|
98
|
+
*/
|
|
99
|
+
export function buildSchtasksConhostArgs(spec: ServiceSpec): string[] {
|
|
100
|
+
const conhost = conhostPath() ?? "C:\\Windows\\System32\\conhost.exe"
|
|
101
|
+
const tr = `"${conhost}" --headless "${spec.runtimeCmd}" "${spec.scriptPath}" --once`
|
|
102
|
+
return ["/Create", "/TN", WIN_TASK_NAME, "/SC", "MINUTE", "/MO", String(spec.intervalMin), "/TR", tr, "/F"]
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function buildSchtasksCreateArgs(spec: ServiceSpec): string[] {
|
|
106
|
+
const tr = `"${spec.runtimeCmd}" "${spec.scriptPath}" --once`
|
|
107
|
+
return ["/Create", "/TN", WIN_TASK_NAME, "/SC", "MINUTE", "/MO", String(spec.intervalMin), "/TR", tr, "/F"]
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function buildSchtasksDeleteArgs(): string[] {
|
|
111
|
+
return ["/Delete", "/TN", WIN_TASK_NAME, "/F"]
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function buildSystemdService(spec: ServiceSpec): string {
|
|
115
|
+
return [
|
|
116
|
+
"[Unit]",
|
|
117
|
+
"Description=OpenCode QQBot watchdog (plugin-managed)",
|
|
118
|
+
"After=default.target",
|
|
119
|
+
"",
|
|
120
|
+
"[Service]",
|
|
121
|
+
"Type=oneshot",
|
|
122
|
+
`ExecStart="${spec.runtimeCmd}" "${spec.scriptPath}" --once`,
|
|
123
|
+
"",
|
|
124
|
+
].join("\n")
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function buildSystemdTimer(intervalMin: number): string {
|
|
128
|
+
return [
|
|
129
|
+
"[Unit]",
|
|
130
|
+
"Description=OpenCode QQBot watchdog timer",
|
|
131
|
+
"",
|
|
132
|
+
"[Timer]",
|
|
133
|
+
"OnBootSec=2min",
|
|
134
|
+
`OnUnitActiveSec=${intervalMin}min`,
|
|
135
|
+
`Unit=${SYSTEMD_UNIT}.service`,
|
|
136
|
+
"",
|
|
137
|
+
"[Install]",
|
|
138
|
+
"WantedBy=timers.target",
|
|
139
|
+
"",
|
|
140
|
+
].join("\n")
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function buildLaunchdPlist(spec: ServiceSpec): string {
|
|
144
|
+
const esc = (s: string): string => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")
|
|
145
|
+
return [
|
|
146
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
147
|
+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
148
|
+
'<plist version="1.0">',
|
|
149
|
+
"<dict>",
|
|
150
|
+
" <key>Label</key>",
|
|
151
|
+
` <string>${LAUNCHD_LABEL}</string>`,
|
|
152
|
+
" <key>ProgramArguments</key>",
|
|
153
|
+
" <array>",
|
|
154
|
+
` <string>${esc(spec.runtimeCmd)}</string>`,
|
|
155
|
+
` <string>${esc(spec.scriptPath)}</string>`,
|
|
156
|
+
" <string>--once</string>",
|
|
157
|
+
" </array>",
|
|
158
|
+
" <key>StartInterval</key>",
|
|
159
|
+
` <integer>${spec.intervalMin * 60}</integer>`,
|
|
160
|
+
" <key>RunAtLoad</key>",
|
|
161
|
+
" <true/>",
|
|
162
|
+
"</dict>",
|
|
163
|
+
"</plist>",
|
|
164
|
+
"",
|
|
165
|
+
].join("\n")
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function systemdDir(): string {
|
|
169
|
+
return join(homedir(), ".config", "systemd", "user")
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function launchdPath(): string {
|
|
173
|
+
return join(homedir(), "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// ---------- 平台执行 ----------
|
|
177
|
+
|
|
178
|
+
/** 查询已注册任务的形态(注册层唯一平台差异点):S4U > conhost --headless > Interactive */
|
|
179
|
+
export function registeredForm(platform = process.platform): "s4u" | "conhost" | "interactive" | "unknown" {
|
|
180
|
+
if (platform !== "win32") return "unknown"
|
|
181
|
+
const q = run("schtasks", ["/Query", "/TN", WIN_TASK_NAME, "/XML"])
|
|
182
|
+
if (!q.ok) return "unknown"
|
|
183
|
+
if (/<LogonType>S4U<\/LogonType>/.test(q.detail)) return "s4u"
|
|
184
|
+
if (q.detail.includes("--headless") && /<Command>[^<]*conhost\.exe/i.test(q.detail)) return "conhost"
|
|
185
|
+
return "interactive"
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export function isS4uRegistered(platform = process.platform): boolean {
|
|
189
|
+
return registeredForm(platform) === "s4u"
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const FORM_LABEL: Record<string, string> = {
|
|
193
|
+
s4u: "S4U(非交互会话,tick 零窗口)",
|
|
194
|
+
conhost: "conhost --headless(隐藏控制台,需已登录会话)",
|
|
195
|
+
interactive: "Interactive(可能闪窗)",
|
|
196
|
+
unknown: "未知形态",
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export function serviceInstall(spec: ServiceSpec, platform = process.platform): CommandResult {
|
|
200
|
+
if (platform === "win32") {
|
|
201
|
+
// 三级梯队(2026-11-09 静默拉起缺陷③):
|
|
202
|
+
// ① XML+S4U(最优,需提权/管理员令牌——未提权实证 Access denied)
|
|
203
|
+
// ② conhost --headless 包装(不需提权、零闪窗、非 shell;需已登录)
|
|
204
|
+
// ③ 旧 Interactive 直调(有看门狗保底,可能闪窗)
|
|
205
|
+
// 每级失败都落到下一级,保证「有看门狗」优先于「看门狗静默」——最终形态在 serviceStatus 可辨。
|
|
206
|
+
const xmlPath = join(tmpdir(), `openqq-watchdog-task-${process.pid}.xml`)
|
|
207
|
+
try {
|
|
208
|
+
// schtasks 的 XML 解析器只接受 UTF-16+UTF-16LE BOM(实证:UTF-8 声名/无 BOM 均「无法切换编码」)
|
|
209
|
+
writeFileSync(xmlPath, Buffer.concat([
|
|
210
|
+
new Uint8Array([0xff, 0xfe]),
|
|
211
|
+
Buffer.from(buildSchtasksTaskXml(spec), "utf-16le"),
|
|
212
|
+
]))
|
|
213
|
+
const res = run("schtasks", buildSchtasksXmlArgs(xmlPath))
|
|
214
|
+
if (res.ok) {
|
|
215
|
+
return { ok: true, detail: `${res.detail}\n注册形态: ${FORM_LABEL.s4u}` }
|
|
216
|
+
}
|
|
217
|
+
const xmlErr = res.detail
|
|
218
|
+
rmSync(xmlPath, { force: true })
|
|
219
|
+
const conhostRes = run("schtasks", buildSchtasksConhostArgs(spec))
|
|
220
|
+
if (conhostRes.ok) {
|
|
221
|
+
return { ok: true, detail: `${conhostRes.detail}\n注册形态: ${FORM_LABEL.conhost}\n(S4U 注册失败,已回退 conhost --headless 梯队,schtasks 原始输出:${xmlErr})` }
|
|
222
|
+
}
|
|
223
|
+
const legacy = run("schtasks", buildSchtasksCreateArgs(spec))
|
|
224
|
+
return {
|
|
225
|
+
...legacy,
|
|
226
|
+
detail: `${legacy.detail}\n(S4U 与 conhost --headless 梯队均失败,已回退 Interactive 形态;S4U 输出:${xmlErr} | conhost 输出:${conhostRes.detail})`,
|
|
227
|
+
}
|
|
228
|
+
} finally {
|
|
229
|
+
try {
|
|
230
|
+
rmSync(xmlPath, { force: true })
|
|
231
|
+
} catch {
|
|
232
|
+
/* 临时文件清理失败不阻断 */
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (platform === "linux") {
|
|
237
|
+
const dir = systemdDir()
|
|
238
|
+
mkdirSync(dir, { recursive: true })
|
|
239
|
+
writeFileSync(join(dir, `${SYSTEMD_UNIT}.service`), buildSystemdService(spec))
|
|
240
|
+
writeFileSync(join(dir, `${SYSTEMD_UNIT}.timer`), buildSystemdTimer(spec.intervalMin))
|
|
241
|
+
const reload = run("systemctl", ["--user", "daemon-reload"])
|
|
242
|
+
if (!reload.ok) return reload
|
|
243
|
+
const enable = run("systemctl", ["--user", "enable", "--now", `${SYSTEMD_UNIT}.timer`])
|
|
244
|
+
return {
|
|
245
|
+
ok: enable.ok,
|
|
246
|
+
detail: `${enable.detail}\n提示:无图形会话时需 loginctl enable-linger $USER 才能常驻`,
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
if (platform === "darwin") {
|
|
250
|
+
const path = launchdPath()
|
|
251
|
+
mkdirSync(join(homedir(), "Library", "LaunchAgents"), { recursive: true })
|
|
252
|
+
writeFileSync(path, buildLaunchdPlist(spec))
|
|
253
|
+
return run("launchctl", ["load", "-w", path])
|
|
254
|
+
}
|
|
255
|
+
return { ok: false, detail: `不支持的平台:${platform}` }
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export function serviceUninstall(platform = process.platform): CommandResult {
|
|
259
|
+
if (platform === "win32") return run("schtasks", buildSchtasksDeleteArgs())
|
|
260
|
+
if (platform === "linux") {
|
|
261
|
+
run("systemctl", ["--user", "disable", "--now", `${SYSTEMD_UNIT}.timer`])
|
|
262
|
+
rmSync(join(systemdDir(), `${SYSTEMD_UNIT}.timer`), { force: true })
|
|
263
|
+
rmSync(join(systemdDir(), `${SYSTEMD_UNIT}.service`), { force: true })
|
|
264
|
+
return run("systemctl", ["--user", "daemon-reload"])
|
|
265
|
+
}
|
|
266
|
+
if (platform === "darwin") {
|
|
267
|
+
const path = launchdPath()
|
|
268
|
+
const res = run("launchctl", ["unload", "-w", path])
|
|
269
|
+
rmSync(path, { force: true })
|
|
270
|
+
return res
|
|
271
|
+
}
|
|
272
|
+
return { ok: false, detail: `不支持的平台:${platform}` }
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export function serviceStatus(platform = process.platform): CommandResult {
|
|
276
|
+
if (platform === "win32") {
|
|
277
|
+
const q = run("schtasks", ["/Query", "/TN", WIN_TASK_NAME])
|
|
278
|
+
const form = q.ok ? `注册形态: ${FORM_LABEL[registeredForm(platform)]}` : "任务未注册"
|
|
279
|
+
return { ...q, detail: `${q.detail}\n${form}` }
|
|
280
|
+
}
|
|
281
|
+
if (platform === "linux") {
|
|
282
|
+
const exists = existsSync(join(systemdDir(), `${SYSTEMD_UNIT}.timer`))
|
|
283
|
+
const active = run("systemctl", ["--user", "is-active", `${SYSTEMD_UNIT}.timer`])
|
|
284
|
+
return { ok: exists && active.ok, detail: `unit 文件存在=${exists}\n${active.detail}` }
|
|
285
|
+
}
|
|
286
|
+
if (platform === "darwin") {
|
|
287
|
+
const path = launchdPath()
|
|
288
|
+
return { ok: existsSync(path), detail: `${path} 存在=${existsSync(path)}\n${run("launchctl", ["list", LAUNCHD_LABEL]).detail}` }
|
|
289
|
+
}
|
|
290
|
+
return { ok: false, detail: `不支持的平台:${platform}` }
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** 读取已安装的 unit/plist 内容(诊断用) */
|
|
294
|
+
export function readInstalledConfig(platform = process.platform): string | null {
|
|
295
|
+
try {
|
|
296
|
+
if (platform === "linux") return readFileSync(join(systemdDir(), `${SYSTEMD_UNIT}.timer`), "utf-8")
|
|
297
|
+
if (platform === "darwin") return readFileSync(launchdPath(), "utf-8")
|
|
298
|
+
return null
|
|
299
|
+
} catch {
|
|
300
|
+
return null
|
|
301
|
+
}
|
|
302
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// @input: argv(--once | --loop | --interval-min N)、~/.openqq 锁/心跳、core/watchdog(superviseOnce)、core/bot-control
|
|
2
|
+
// @output: (side-effect) 巡检并在必要时重启 bot;give-up 时 QQ 告警
|
|
3
|
+
// @pos: cli - 跨平台监督者入口(dist/openqq-watchdog.js)
|
|
4
|
+
//
|
|
5
|
+
// 用法:
|
|
6
|
+
// node dist/openqq-watchdog.js --once # 单次巡检(自启项/timer 调这个)
|
|
7
|
+
// node dist/openqq-watchdog.js --loop # 常驻循环(默认 10 分钟)
|
|
8
|
+
// node dist/openqq-watchdog.js --interval-min 5 # 自定义周期
|
|
9
|
+
// 退出码:0=正常(含"健康/冷却/让行");1=运行时/配置错误。
|
|
10
|
+
//
|
|
11
|
+
// 2026-11-09 重构:裸 healOnce 升级为 superviseOnce——优雅杀(TERM→宽限→KILL)、
|
|
12
|
+
// 冷却(防互踢)、重启强度(超限 give-up 并告警,不当永动机)、监督者认领互斥。
|
|
13
|
+
import { botWatchdogPaths, readEnvField, appendWatchdogLog, superviseOnce } from "../core/watchdog.js"
|
|
14
|
+
import { readAppId, startBot } from "../core/bot-control.js"
|
|
15
|
+
import { runNotifyCli } from "./notify.js"
|
|
16
|
+
import { join } from "path"
|
|
17
|
+
import { homedir } from "os"
|
|
18
|
+
|
|
19
|
+
const DEFAULT_INTERVAL_MIN = 10
|
|
20
|
+
|
|
21
|
+
function parseArgs(argv: string[]): { loop: boolean; intervalMin: number } {
|
|
22
|
+
const loop = argv.includes("--loop")
|
|
23
|
+
const idx = argv.indexOf("--interval-min")
|
|
24
|
+
const raw = idx >= 0 ? Number(argv[idx + 1]) : Number.NaN
|
|
25
|
+
const intervalMin = Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_INTERVAL_MIN
|
|
26
|
+
return { loop, intervalMin }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function currentAppId(): string | null {
|
|
30
|
+
return readAppId() ?? readEnvField(join(homedir(), ".openqq", ".env"), "QQ_APP_ID")
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** give-up 上报:入队 QQ 通知(bot 恢复后送达)+本进程日志;失败静默(fail-open)。 */
|
|
34
|
+
function alert(message: string): void {
|
|
35
|
+
void runNotifyCli(["--text", message, "--id", `supervisor-giveup-${Date.now()}`]).then(
|
|
36
|
+
(r) => console.log(`[supervisor] 告警已入队 user=${r.user}`),
|
|
37
|
+
(error) => console.error("[supervisor] 告警入队失败:", error instanceof Error ? error.message : error),
|
|
38
|
+
)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function tick(appId: string): Promise<void> {
|
|
42
|
+
const result = await superviseOnce({
|
|
43
|
+
paths: botWatchdogPaths(appId),
|
|
44
|
+
spawn: () => startBot(import.meta.url, (line) => console.log(line)),
|
|
45
|
+
log: (line) => console.log(line),
|
|
46
|
+
alert,
|
|
47
|
+
})
|
|
48
|
+
console.log(`[supervisor] ${result.action}:${result.detail}`)
|
|
49
|
+
// 健康时静默落盘(避免每 10 分钟一行膨胀日志),异常必记
|
|
50
|
+
if (result.action !== "ok") appendWatchdogLog(`[supervisor] ${result.action}:${result.detail}`)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function main(): Promise<void> {
|
|
54
|
+
const args = parseArgs(process.argv.slice(2))
|
|
55
|
+
const appId = currentAppId()
|
|
56
|
+
if (!appId) {
|
|
57
|
+
console.error("[watchdog] 未找到 QQ_APP_ID(~/.openqq/.env),无法定位实例锁")
|
|
58
|
+
process.exit(1)
|
|
59
|
+
}
|
|
60
|
+
console.log(`[watchdog] 模式=${args.loop ? `loop/${args.intervalMin}min` : "once"}(监督矩阵:冷却2m/强度3次15m/优雅杀8s)`)
|
|
61
|
+
await tick(appId)
|
|
62
|
+
if (!args.loop) return
|
|
63
|
+
const timer = setInterval(() => {
|
|
64
|
+
void tick(appId).catch((error) => console.error("[watchdog] 巡检失败:", error instanceof Error ? error.message : error))
|
|
65
|
+
}, args.intervalMin * 60_000)
|
|
66
|
+
const stop = (): void => {
|
|
67
|
+
clearInterval(timer)
|
|
68
|
+
process.exit(0)
|
|
69
|
+
}
|
|
70
|
+
process.once("SIGINT", stop)
|
|
71
|
+
process.once("SIGTERM", stop)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
void main().catch((error) => {
|
|
75
|
+
console.error("[watchdog] 致命错误:", error instanceof Error ? error.message : error)
|
|
76
|
+
process.exit(1)
|
|
77
|
+
})
|