@linjz/opencode-qqbot 0.3.14 → 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 +73 -5
- package/bin/openqq.js +34 -0
- package/dist/notify-cli.js +593 -0
- package/dist/opencode-qqbot-plugin.js +938 -65
- package/dist/openqq-bot.js +3585 -717
- package/dist/openqq-cli.js +791 -0
- package/dist/openqq-watchdog.js +1063 -0
- package/package.json +9 -5
- package/src/bridge.ts +1338 -157
- package/src/cli/notify-main.ts +6 -0
- package/src/cli/notify.ts +167 -0
- 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 +87 -2
- 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 +16 -7
- 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 +21 -6
- 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 -0
- package/src/core/outbox.ts +10 -9
- package/src/core/permission.ts +627 -301
- 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 -112
- package/src/qq/api.ts +165 -61
- package/src/qq/gateway.ts +80 -17
- package/src/qq/media.ts +5 -1
- package/src/qq/sender.ts +30 -18
- package/src/qq/types.ts +7 -0
|
@@ -0,0 +1,791 @@
|
|
|
1
|
+
// src/cli/openqq-main.ts
|
|
2
|
+
import { existsSync as existsSync4 } from "fs";
|
|
3
|
+
import { dirname as dirname3, join as join5 } from "path";
|
|
4
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
5
|
+
|
|
6
|
+
// src/core/bot-control.ts
|
|
7
|
+
import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
|
|
8
|
+
import { dirname as dirname2, join as join3 } from "path";
|
|
9
|
+
import { homedir as homedir3 } from "os";
|
|
10
|
+
import { fileURLToPath } from "url";
|
|
11
|
+
|
|
12
|
+
// src/core/bot-launcher.ts
|
|
13
|
+
import { spawn, spawnSync } from "child_process";
|
|
14
|
+
import { existsSync, readFileSync, statSync } from "fs";
|
|
15
|
+
import { join, dirname, isAbsolute } from "path";
|
|
16
|
+
import { homedir } from "os";
|
|
17
|
+
function resolveRuntime(probe = defaultProbe) {
|
|
18
|
+
if (resolveBunCommand(probe))
|
|
19
|
+
return "bun";
|
|
20
|
+
if (probe("node"))
|
|
21
|
+
return "node";
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
function isExecutable(p) {
|
|
25
|
+
try {
|
|
26
|
+
const st = statSync(p);
|
|
27
|
+
return st.isFile() && (process.platform === "win32" || (st.mode & 73) !== 0);
|
|
28
|
+
} catch {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function locateOnPath(cmd, pathEnv = process.env.PATH ?? process.env.Path ?? "") {
|
|
33
|
+
if (isAbsolute(cmd))
|
|
34
|
+
return isExecutable(cmd) ? cmd : null;
|
|
35
|
+
const isWin = process.platform === "win32";
|
|
36
|
+
for (const dir of pathEnv.split(isWin ? ";" : ":")) {
|
|
37
|
+
if (!dir)
|
|
38
|
+
continue;
|
|
39
|
+
const base = isWin && !/\.[a-z]+$/i.test(cmd) ? `${cmd}.exe` : cmd;
|
|
40
|
+
const full = join(dir, base);
|
|
41
|
+
if (isExecutable(full))
|
|
42
|
+
return full;
|
|
43
|
+
}
|
|
44
|
+
if (isWin)
|
|
45
|
+
return resolveThroughShim(cmd, pathEnv);
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
var SHIM_PATTERN_LINE = /%~?dp0%?\\?([^"\n]+?\.exe)/;
|
|
49
|
+
var SHIM_PATTERN_ABS = /([A-Za-z]:\\[^\n"]+?\.exe)/;
|
|
50
|
+
function resolveThroughShim(bare, pathEnv = process.env.PATH ?? process.env.Path ?? "") {
|
|
51
|
+
for (const dir of pathEnv.split(";")) {
|
|
52
|
+
if (!dir)
|
|
53
|
+
continue;
|
|
54
|
+
for (const ext of [".cmd", ".bat"]) {
|
|
55
|
+
const shimPath = join(dir, bare + ext);
|
|
56
|
+
let text;
|
|
57
|
+
try {
|
|
58
|
+
text = readFileSync(shimPath, "utf-8");
|
|
59
|
+
} catch {
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
const rel = SHIM_PATTERN_LINE.exec(text);
|
|
63
|
+
if (rel) {
|
|
64
|
+
const full = join(dir, rel[1]);
|
|
65
|
+
if (isExecutable(full))
|
|
66
|
+
return full;
|
|
67
|
+
}
|
|
68
|
+
const abs = SHIM_PATTERN_ABS.exec(text);
|
|
69
|
+
if (abs) {
|
|
70
|
+
const full = abs[1];
|
|
71
|
+
if (isExecutable(full))
|
|
72
|
+
return full;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
function bunCandidates() {
|
|
79
|
+
if (process.platform === "win32") {
|
|
80
|
+
const appdata = process.env.APPDATA || join(homedir(), "AppData", "Roaming");
|
|
81
|
+
return [
|
|
82
|
+
join(appdata, "npm", "node_modules", "bun", "bin", "bun.exe"),
|
|
83
|
+
join(homedir(), ".bun", "bin", "bun.exe"),
|
|
84
|
+
"bun",
|
|
85
|
+
"bun.exe"
|
|
86
|
+
];
|
|
87
|
+
}
|
|
88
|
+
return ["/usr/local/bin/bun", "/opt/homebrew/bin/bun", join(homedir(), ".bun", "bin", "bun"), "bun"];
|
|
89
|
+
}
|
|
90
|
+
function resolveBunCommand(probe = defaultProbe) {
|
|
91
|
+
if (probe !== defaultProbe) {
|
|
92
|
+
for (const c of bunCandidates()) {
|
|
93
|
+
if (!probe(c))
|
|
94
|
+
continue;
|
|
95
|
+
if (isAbsolute(c))
|
|
96
|
+
return c;
|
|
97
|
+
return locateOnPath(c) ?? resolveThroughShim(c) ?? null;
|
|
98
|
+
}
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
for (const c of bunCandidates()) {
|
|
102
|
+
const full = locateOnPath(c) ?? (isAbsolute(c) ? null : resolveThroughShim(c));
|
|
103
|
+
if (full)
|
|
104
|
+
return full;
|
|
105
|
+
}
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
function defaultProbe(cmd) {
|
|
109
|
+
try {
|
|
110
|
+
const r = spawnSync(cmd, ["--version"], { stdio: "ignore", windowsHide: true });
|
|
111
|
+
return r.status === 0;
|
|
112
|
+
} catch {
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function resolveRuntimeCommand(runtime) {
|
|
117
|
+
const cmd = runtime === "bun" ? resolveBunCommand() : locateOnPath("node");
|
|
118
|
+
if (!cmd)
|
|
119
|
+
throw new Error(`未找到 ${runtime} 可执行体(全路径解析失败),拒绝生成裸名拉起计划`);
|
|
120
|
+
return cmd;
|
|
121
|
+
}
|
|
122
|
+
function buildLaunchPlan(runtime, entry, logPath) {
|
|
123
|
+
const CONFIG_KEY = [/^QQ_/, /^OPENCODE_/, /^ALLOWED_USERS$/];
|
|
124
|
+
const inherited = {};
|
|
125
|
+
for (const [k, v] of Object.entries(process.env)) {
|
|
126
|
+
if (v === undefined)
|
|
127
|
+
continue;
|
|
128
|
+
if (CONFIG_KEY.some((r) => r.test(k)))
|
|
129
|
+
continue;
|
|
130
|
+
inherited[k] = v;
|
|
131
|
+
}
|
|
132
|
+
const env = {
|
|
133
|
+
...inherited,
|
|
134
|
+
QQ_INSTANCE_LOCK: "try",
|
|
135
|
+
...logPath ? { QQ_LOG_FILE: logPath } : {}
|
|
136
|
+
};
|
|
137
|
+
if (runtime === "bun") {
|
|
138
|
+
return { command: resolveRuntimeCommand("bun"), args: ["run", entry], env };
|
|
139
|
+
}
|
|
140
|
+
return { command: resolveRuntimeCommand("node"), args: [entry], env };
|
|
141
|
+
}
|
|
142
|
+
function botLogPath() {
|
|
143
|
+
return join(homedir(), ".openqq", "bot.out.log");
|
|
144
|
+
}
|
|
145
|
+
function spawnBotDetached(plan) {
|
|
146
|
+
const child = spawn(plan.command, plan.args, {
|
|
147
|
+
detached: true,
|
|
148
|
+
stdio: "ignore",
|
|
149
|
+
env: plan.env,
|
|
150
|
+
windowsHide: true,
|
|
151
|
+
shell: false
|
|
152
|
+
});
|
|
153
|
+
child.unref();
|
|
154
|
+
if (typeof child.pid !== "number")
|
|
155
|
+
throw new Error("spawn 未返回 pid");
|
|
156
|
+
return child.pid;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// src/core/watchdog.ts
|
|
160
|
+
import { readFileSync as readFileSync2, statSync as statSync2, unlinkSync, writeFileSync } from "fs";
|
|
161
|
+
import { join as join2 } from "path";
|
|
162
|
+
import { homedir as homedir2 } from "os";
|
|
163
|
+
var HEARTBEAT_STALE_MS = 5 * 60000;
|
|
164
|
+
function botWatchdogPaths(appId) {
|
|
165
|
+
const dir = join2(homedir2(), ".openqq");
|
|
166
|
+
return { lockPath: join2(dir, `openqq-${appId}.lock`), heartbeatPath: join2(dir, "heartbeat") };
|
|
167
|
+
}
|
|
168
|
+
function isPidAlive(pid) {
|
|
169
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
170
|
+
return false;
|
|
171
|
+
try {
|
|
172
|
+
process.kill(pid, 0);
|
|
173
|
+
return true;
|
|
174
|
+
} catch (error) {
|
|
175
|
+
return error.code === "EPERM";
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
function ageOf(path, now) {
|
|
179
|
+
try {
|
|
180
|
+
return Math.max(0, now - statSync2(path).mtimeMs);
|
|
181
|
+
} catch {
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
function readBotHealth(paths, now = Date.now()) {
|
|
186
|
+
const lockAgeMs = ageOf(paths.lockPath, now);
|
|
187
|
+
let lockPid = null;
|
|
188
|
+
if (lockAgeMs !== null) {
|
|
189
|
+
try {
|
|
190
|
+
const raw = JSON.parse(readFileSync2(paths.lockPath, "utf-8"));
|
|
191
|
+
if (typeof raw.pid === "number" && Number.isInteger(raw.pid))
|
|
192
|
+
lockPid = raw.pid;
|
|
193
|
+
} catch {}
|
|
194
|
+
}
|
|
195
|
+
return {
|
|
196
|
+
lockPid,
|
|
197
|
+
lockAgeMs,
|
|
198
|
+
pidAlive: lockPid === null ? null : isPidAlive(lockPid),
|
|
199
|
+
heartbeatAgeMs: ageOf(paths.heartbeatPath, now)
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
function appendWatchdogLog(line) {
|
|
203
|
+
try {
|
|
204
|
+
const dir = join2(homedir2(), ".openqq");
|
|
205
|
+
writeFileSync(join2(dir, "watchdog.log"), `${new Date().toISOString()} ${line}
|
|
206
|
+
`, { flag: "a" });
|
|
207
|
+
} catch {}
|
|
208
|
+
}
|
|
209
|
+
var DEFAULT_SUPERVISOR_POLICY = {
|
|
210
|
+
cooldownMs: 2 * 60000,
|
|
211
|
+
maxRestarts: 3,
|
|
212
|
+
windowMs: 15 * 60000,
|
|
213
|
+
graceMs: 8000,
|
|
214
|
+
claimTtlMs: 90000
|
|
215
|
+
};
|
|
216
|
+
function decideSupervise(health, state, now, policy = DEFAULT_SUPERVISOR_POLICY) {
|
|
217
|
+
const staleHeartbeat = health.heartbeatAgeMs !== null && health.heartbeatAgeMs > HEARTBEAT_STALE_MS;
|
|
218
|
+
const needsRestart = health.lockPid === null || health.pidAlive === false || staleHeartbeat;
|
|
219
|
+
if (!needsRestart)
|
|
220
|
+
return { kind: "ok" };
|
|
221
|
+
const windowStart = now - policy.windowMs;
|
|
222
|
+
const recentRestarts = state.restartLog.filter((t) => t > windowStart).length;
|
|
223
|
+
if (recentRestarts >= policy.maxRestarts)
|
|
224
|
+
return { kind: "give-up", restarts: recentRestarts };
|
|
225
|
+
const last = state.restartLog[state.restartLog.length - 1] ?? null;
|
|
226
|
+
if (last !== null && now - last < policy.cooldownMs)
|
|
227
|
+
return { kind: "cooldown", untilMs: last + policy.cooldownMs };
|
|
228
|
+
if (health.lockPid !== null && health.pidAlive !== false && staleHeartbeat) {
|
|
229
|
+
return {
|
|
230
|
+
kind: "grace-kill-spawn",
|
|
231
|
+
killPid: health.lockPid,
|
|
232
|
+
reason: `心跳陈旧 ${Math.round((health.heartbeatAgeMs ?? 0) / 60000)} 分钟(进程活但事件循环无进展)`
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
return { kind: "spawn", reason: health.lockPid === null ? "无实例锁(bot 未运行)" : "锁定进程已退出" };
|
|
236
|
+
}
|
|
237
|
+
var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
238
|
+
var defaultSupervisorKill = (pid, signal) => {
|
|
239
|
+
try {
|
|
240
|
+
process.kill(pid, signal);
|
|
241
|
+
} catch {}
|
|
242
|
+
};
|
|
243
|
+
function readJson(path, fallback) {
|
|
244
|
+
try {
|
|
245
|
+
return { ...fallback, ...JSON.parse(readFileSync2(path, "utf-8")) };
|
|
246
|
+
} catch {
|
|
247
|
+
return fallback;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
async function superviseOnce(deps) {
|
|
251
|
+
const policy = deps.policy ?? DEFAULT_SUPERVISOR_POLICY;
|
|
252
|
+
const now = deps.now?.() ?? Date.now();
|
|
253
|
+
const log = deps.log ?? (() => {});
|
|
254
|
+
const sleep = deps.sleep ?? defaultSleep;
|
|
255
|
+
const kill = deps.kill ?? defaultSupervisorKill;
|
|
256
|
+
const isAlive = deps.isAlive ?? isPidAlive;
|
|
257
|
+
const statePath = deps.statePath ?? join2(homedir2(), ".openqq", "supervisor.json");
|
|
258
|
+
const claimPath = deps.claimPath ?? join2(homedir2(), ".openqq", "supervisor.lock");
|
|
259
|
+
const audit = (line) => {
|
|
260
|
+
if (deps.auditLogPath) {
|
|
261
|
+
try {
|
|
262
|
+
writeFileSync(deps.auditLogPath, `${new Date().toISOString()} ${line}
|
|
263
|
+
`, { flag: "a" });
|
|
264
|
+
return;
|
|
265
|
+
} catch {}
|
|
266
|
+
}
|
|
267
|
+
appendWatchdogLog(line);
|
|
268
|
+
};
|
|
269
|
+
const claim = readJson(claimPath, { pid: 0, ts: 0 });
|
|
270
|
+
if (claim.ts && now - claim.ts < policy.claimTtlMs && claim.pid !== process.pid) {
|
|
271
|
+
return { action: "yield", detail: `监督者 pid=${claim.pid} 持锁中`, killedPid: null, spawnedPid: null };
|
|
272
|
+
}
|
|
273
|
+
try {
|
|
274
|
+
writeFileSync(claimPath, JSON.stringify({ pid: process.pid, ts: now }));
|
|
275
|
+
} catch {
|
|
276
|
+
return { action: "yield", detail: "认领锁不可写", killedPid: null, spawnedPid: null };
|
|
277
|
+
}
|
|
278
|
+
const release = () => {
|
|
279
|
+
try {
|
|
280
|
+
writeFileSync(claimPath, JSON.stringify({ pid: 0, ts: 0 }));
|
|
281
|
+
} catch {}
|
|
282
|
+
};
|
|
283
|
+
try {
|
|
284
|
+
const health = readBotHealth(deps.paths, now);
|
|
285
|
+
const state = readJson(statePath, { restartLog: [] });
|
|
286
|
+
let action = decideSupervise(health, state, now, policy);
|
|
287
|
+
if (deps.request === "manual-restart" && action.kind === "ok") {
|
|
288
|
+
const windowStart = now - policy.windowMs;
|
|
289
|
+
const recentRestarts = state.restartLog.filter((t) => t > windowStart).length;
|
|
290
|
+
if (recentRestarts >= policy.maxRestarts) {
|
|
291
|
+
return {
|
|
292
|
+
action: "give-up",
|
|
293
|
+
detail: `15 分钟内已重启 ${recentRestarts} 次(监督强度上限),人工重启亦被拦截,请排查根因`,
|
|
294
|
+
killedPid: null,
|
|
295
|
+
spawnedPid: null
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
const last = state.restartLog[state.restartLog.length - 1] ?? null;
|
|
299
|
+
if (last !== null && now - last < policy.cooldownMs) {
|
|
300
|
+
return { action: "cooldown", detail: `距上次重启不足 ${Math.round(policy.cooldownMs / 1000)}s(冷却期),人工重启跳过`, killedPid: null, spawnedPid: null };
|
|
301
|
+
}
|
|
302
|
+
action = health.lockPid !== null && health.pidAlive !== false ? { kind: "grace-kill-spawn", killPid: health.lockPid, reason: "人工请求重启(openqq restart)" } : { kind: "spawn", reason: "人工请求重启(bot 未运行,直接拉起)" };
|
|
303
|
+
}
|
|
304
|
+
if (action.kind === "ok")
|
|
305
|
+
return { action: "ok", detail: "健康", killedPid: null, spawnedPid: null };
|
|
306
|
+
if (action.kind === "cooldown") {
|
|
307
|
+
log(`[supervisor] 冷却中(上次重启 ${Math.round((now - (action.untilMs - policy.cooldownMs)) / 1000)}s 前),本轮跳过`);
|
|
308
|
+
return { action: "cooldown", detail: "冷却跳过", killedPid: null, spawnedPid: null };
|
|
309
|
+
}
|
|
310
|
+
if (action.kind === "yield") {
|
|
311
|
+
return { action: "yield", detail: action.reason, killedPid: null, spawnedPid: null };
|
|
312
|
+
}
|
|
313
|
+
if (action.kind === "give-up") {
|
|
314
|
+
const message = `⚠️ QQBot 看门狗已放弃:${action.restarts} 次重启/${Math.round(policy.windowMs / 60000)} 分钟仍不健康。继续自动重启没有意义(同因反复死亡),请人工检查 %TEMP%\\opencode 下 bot.out.log 与 ~/.openqq/watchdog.log。`;
|
|
315
|
+
audit(`give-up:${message}`);
|
|
316
|
+
log(`[supervisor] give-up:${action.restarts} 次重启仍异常,停止循环并上报`);
|
|
317
|
+
const lastAlert = state.alertedAt ?? 0;
|
|
318
|
+
if (now - lastAlert > 30 * 60000) {
|
|
319
|
+
try {
|
|
320
|
+
deps.alert?.(message);
|
|
321
|
+
state.alertedAt = now;
|
|
322
|
+
writeFileSync(statePath, JSON.stringify(state));
|
|
323
|
+
} catch {}
|
|
324
|
+
}
|
|
325
|
+
return { action: "give-up", detail: message, killedPid: null, spawnedPid: null };
|
|
326
|
+
}
|
|
327
|
+
let killedPid = null;
|
|
328
|
+
if (action.kind === "grace-kill-spawn" && action.killPid !== process.pid) {
|
|
329
|
+
const pid = action.killPid;
|
|
330
|
+
if (deps.request !== "manual-restart") {
|
|
331
|
+
await sleep(300);
|
|
332
|
+
const recheck = readBotHealth(deps.paths, Date.now());
|
|
333
|
+
const recheckFresh = recheck.heartbeatAgeMs !== null && recheck.heartbeatAgeMs <= HEARTBEAT_STALE_MS;
|
|
334
|
+
if (recheck.pidAlive !== false && recheckFresh) {
|
|
335
|
+
const ageSec = Math.round((recheck.heartbeatAgeMs ?? 0) / 1000);
|
|
336
|
+
audit(`杀前复核改判 ok:pid=${pid} 心跳已恢复(年龄 ${ageSec}s),放弃误杀`);
|
|
337
|
+
log(`[supervisor] 杀前复核改判 ok:心跳已恢复(${ageSec}s),放弃杀 pid=${pid}`);
|
|
338
|
+
return { action: "ok", detail: `杀前复核:心跳已恢复,放弃误杀 pid=${pid}`, killedPid: null, spawnedPid: null };
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
kill(pid, "SIGTERM");
|
|
342
|
+
const deadline = now + policy.graceMs;
|
|
343
|
+
let alive = isAlive(pid);
|
|
344
|
+
while (alive && Date.now() < deadline) {
|
|
345
|
+
await sleep(250);
|
|
346
|
+
alive = isAlive(pid);
|
|
347
|
+
}
|
|
348
|
+
if (alive) {
|
|
349
|
+
kill(pid, "SIGKILL");
|
|
350
|
+
const hardDeadline = Date.now() + 3000;
|
|
351
|
+
while (alive && Date.now() < hardDeadline) {
|
|
352
|
+
await sleep(250);
|
|
353
|
+
alive = isAlive(pid);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
if (alive) {
|
|
357
|
+
audit(`give-up-kill:pid=${pid} 无法终止(权限/系统级),本次不拉起`);
|
|
358
|
+
return { action: "give-up", detail: `pid=${pid} 无法终止`, killedPid: null, spawnedPid: null };
|
|
359
|
+
}
|
|
360
|
+
killedPid = pid;
|
|
361
|
+
}
|
|
362
|
+
try {
|
|
363
|
+
if (killedPid !== null || health.lockPid === null || health.pidAlive === false) {
|
|
364
|
+
unlinkSync(deps.paths.lockPath);
|
|
365
|
+
audit(`清锁:${deps.paths.lockPath}(${action.reason})`);
|
|
366
|
+
}
|
|
367
|
+
} catch {}
|
|
368
|
+
const spawnedPid = deps.spawn();
|
|
369
|
+
state.restartLog.push(Date.now());
|
|
370
|
+
state.restartLog = state.restartLog.filter((t) => t > Date.now() - policy.windowMs * 2);
|
|
371
|
+
try {
|
|
372
|
+
writeFileSync(statePath, JSON.stringify(state));
|
|
373
|
+
} catch {
|
|
374
|
+
log("[supervisor] 强度账落盘失败(不影响本次拉起)");
|
|
375
|
+
}
|
|
376
|
+
const detail = `${action.reason};${killedPid ? `已优雅停 pid=${killedPid};` : ""}已拉起 pid=${spawnedPid}`;
|
|
377
|
+
audit(killedPid ? `主动杀:${detail}` : `验尸拉新:${detail}`);
|
|
378
|
+
return { action: "restart", detail, killedPid, spawnedPid };
|
|
379
|
+
} finally {
|
|
380
|
+
release();
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// src/core/bot-control.ts
|
|
385
|
+
function resolveInstalledBotEntry(fromUrl, exists = existsSync2) {
|
|
386
|
+
const here = dirname2(fileURLToPath(fromUrl));
|
|
387
|
+
const candidates = [
|
|
388
|
+
join3(here, "openqq-bot.js"),
|
|
389
|
+
join3(here, "..", "dist", "openqq-bot.js"),
|
|
390
|
+
join3(here, "..", "src", "index.ts"),
|
|
391
|
+
join3(here, "..", "..", "src", "index.ts")
|
|
392
|
+
];
|
|
393
|
+
for (const c of candidates)
|
|
394
|
+
if (exists(c))
|
|
395
|
+
return c;
|
|
396
|
+
return null;
|
|
397
|
+
}
|
|
398
|
+
function readAppId(envPath = join3(homedir3(), ".openqq", ".env")) {
|
|
399
|
+
try {
|
|
400
|
+
for (const line of readFileSync3(envPath, "utf-8").split(`
|
|
401
|
+
`)) {
|
|
402
|
+
const t = line.trim();
|
|
403
|
+
if (!t || t.startsWith("#"))
|
|
404
|
+
continue;
|
|
405
|
+
const eq = t.indexOf("=");
|
|
406
|
+
if (eq > 0 && t.slice(0, eq).trim() === "QQ_APP_ID")
|
|
407
|
+
return t.slice(eq + 1).trim() || null;
|
|
408
|
+
}
|
|
409
|
+
} catch {}
|
|
410
|
+
return null;
|
|
411
|
+
}
|
|
412
|
+
function inflightPath() {
|
|
413
|
+
return join3(homedir3(), ".openqq", "inflight.json");
|
|
414
|
+
}
|
|
415
|
+
function countInflight(path = inflightPath()) {
|
|
416
|
+
try {
|
|
417
|
+
const raw = JSON.parse(readFileSync3(path, "utf-8"));
|
|
418
|
+
if (!Array.isArray(raw))
|
|
419
|
+
return 0;
|
|
420
|
+
return raw.filter((e) => e.state === "inflight").length;
|
|
421
|
+
} catch {
|
|
422
|
+
return 0;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
async function waitUntilIdle(opts) {
|
|
426
|
+
const timeoutMs = opts?.timeoutMs ?? 60 * 60000;
|
|
427
|
+
const pollMs = opts?.pollMs ?? 1e4;
|
|
428
|
+
const started = Date.now();
|
|
429
|
+
for (;; ) {
|
|
430
|
+
const n = countInflight();
|
|
431
|
+
if (n === 0)
|
|
432
|
+
return true;
|
|
433
|
+
const elapsed = Date.now() - started;
|
|
434
|
+
if (elapsed >= timeoutMs)
|
|
435
|
+
return false;
|
|
436
|
+
opts?.onWait?.(n, elapsed);
|
|
437
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
function startBot(fromUrl, log = () => {}) {
|
|
441
|
+
const entry = resolveInstalledBotEntry(fromUrl);
|
|
442
|
+
if (!entry)
|
|
443
|
+
throw new Error("未找到 bot 入口(dist/openqq-bot.js 或 src/index.ts)——安装不完整");
|
|
444
|
+
const runtime = resolveRuntime();
|
|
445
|
+
if (!runtime)
|
|
446
|
+
throw new Error("未找到 bun/node 运行时");
|
|
447
|
+
const plan = buildLaunchPlan(runtime, entry, botLogPath());
|
|
448
|
+
const pid = spawnBotDetached(plan);
|
|
449
|
+
log(`[bot-control] 已拉起 pid=${pid}(runtime=${runtime},entry=${entry})`);
|
|
450
|
+
return pid;
|
|
451
|
+
}
|
|
452
|
+
async function restartBot(opts) {
|
|
453
|
+
const log = opts.log ?? (() => {});
|
|
454
|
+
const appId = readAppId();
|
|
455
|
+
if (!appId)
|
|
456
|
+
throw new Error("缺少 ~/.openqq/.env 的 QQ_APP_ID,无法定位实例锁");
|
|
457
|
+
if (!opts.force) {
|
|
458
|
+
const idle = await waitUntilIdle({
|
|
459
|
+
timeoutMs: opts.timeoutMs,
|
|
460
|
+
onWait: (n, elapsed) => log(`[bot-control] 仍在途 ${n} 条(已等 ${Math.round(elapsed / 1000)}s),继续等待空闲`)
|
|
461
|
+
});
|
|
462
|
+
if (!idle) {
|
|
463
|
+
log("[bot-control] 等待空闲超时:本次不重启(需要时用 --force)");
|
|
464
|
+
return { action: "skipped", killedPid: null, spawnedPid: null, reason: "等待空闲超时" };
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
const r = await superviseOnce({
|
|
468
|
+
paths: botWatchdogPaths(appId),
|
|
469
|
+
request: "manual-restart",
|
|
470
|
+
spawn: () => startBot(opts.spawnFromUrl, log),
|
|
471
|
+
log
|
|
472
|
+
});
|
|
473
|
+
switch (r.action) {
|
|
474
|
+
case "restart":
|
|
475
|
+
return { action: "restarted", killedPid: r.killedPid, spawnedPid: r.spawnedPid, reason: opts.force ? "force(经监督矩阵)" : "idle(经监督矩阵)" };
|
|
476
|
+
case "cooldown":
|
|
477
|
+
return { action: "skipped", killedPid: null, spawnedPid: null, reason: `监督矩阵冷却跳过:${r.detail}` };
|
|
478
|
+
case "give-up":
|
|
479
|
+
return { action: "skipped", killedPid: null, spawnedPid: null, reason: `监督矩阵 give-up:${r.detail}` };
|
|
480
|
+
case "yield":
|
|
481
|
+
return { action: "skipped", killedPid: null, spawnedPid: null, reason: `认领互斥:${r.detail}` };
|
|
482
|
+
default:
|
|
483
|
+
return { action: "skipped", killedPid: null, spawnedPid: null, reason: `无需动作:${r.detail}` };
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// src/cli/service-main.ts
|
|
488
|
+
import { spawnSync as spawnSync2 } from "child_process";
|
|
489
|
+
import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync4, rmSync, statSync as statSync3, writeFileSync as writeFileSync2 } from "fs";
|
|
490
|
+
import { homedir as homedir4, tmpdir } from "os";
|
|
491
|
+
import { join as join4 } from "path";
|
|
492
|
+
var WIN_TASK_NAME = "OpenQQBotWatchdog";
|
|
493
|
+
var SYSTEMD_UNIT = "openqq-watchdog";
|
|
494
|
+
var LAUNCHD_LABEL = "com.linjp.opencode-qqbot.watchdog";
|
|
495
|
+
function run(cmd, args) {
|
|
496
|
+
try {
|
|
497
|
+
const r = spawnSync2(cmd, args, { encoding: "utf-8", windowsHide: true });
|
|
498
|
+
const detail = `${cmd} ${args.join(" ")}
|
|
499
|
+
${(r.stdout ?? "").trim()}${(r.stderr ?? "").trim() ? `
|
|
500
|
+
${r.stderr.trim()}` : ""}`;
|
|
501
|
+
return { ok: r.status === 0, detail };
|
|
502
|
+
} catch (error) {
|
|
503
|
+
return { ok: false, detail: `执行失败:${error instanceof Error ? error.message : String(error)}` };
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
var escXml = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
507
|
+
function buildSchtasksTaskXml(spec, now = new Date) {
|
|
508
|
+
const user = escXml(process.env.USERNAME ?? "SYSTEM");
|
|
509
|
+
const trigger = `<TimeTrigger><StartBoundary>${now.toISOString()}</StartBoundary>` + `<Repetition><Interval>PT${spec.intervalMin}M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition>` + `<Enabled>true</Enabled></TimeTrigger>`;
|
|
510
|
+
return [
|
|
511
|
+
'<?xml version="1.0" encoding="UTF-16"?>',
|
|
512
|
+
'<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',
|
|
513
|
+
`<RegistrationInfo><Author>${user}</Author><Description>OpenCode QQBot watchdog (plugin-managed, silent)</Description></RegistrationInfo>`,
|
|
514
|
+
`<Triggers>${trigger}</Triggers>`,
|
|
515
|
+
'<Principals><Principal id="Author">' + `<UserId>${user}</UserId><LogonType>S4U</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>`,
|
|
516
|
+
"<Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>" + "<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>" + "<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>" + "<ExecutionTimeLimit>PT5M</ExecutionTimeLimit><StartWhenAvailable>true</StartWhenAvailable>" + "<Enabled>true</Enabled></Settings>",
|
|
517
|
+
'<Actions Context="Author"><Exec>' + `<Command>${escXml(spec.runtimeCmd)}</Command>` + `<Arguments>${escXml(`"${spec.scriptPath}" --once`)}</Arguments>` + "</Exec></Actions>",
|
|
518
|
+
"</Task>",
|
|
519
|
+
""
|
|
520
|
+
].join(`
|
|
521
|
+
`);
|
|
522
|
+
}
|
|
523
|
+
function buildSchtasksXmlArgs(xmlPath) {
|
|
524
|
+
return ["/Create", "/TN", WIN_TASK_NAME, "/XML", xmlPath, "/F"];
|
|
525
|
+
}
|
|
526
|
+
function conhostPath(platform = process.platform) {
|
|
527
|
+
if (platform !== "win32")
|
|
528
|
+
return null;
|
|
529
|
+
const p = join4(process.env.SystemRoot ?? "C:\\Windows", "System32", "conhost.exe");
|
|
530
|
+
try {
|
|
531
|
+
return statSync3(p).isFile() ? p : null;
|
|
532
|
+
} catch {
|
|
533
|
+
return null;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
function buildSchtasksConhostArgs(spec) {
|
|
537
|
+
const conhost = conhostPath() ?? "C:\\Windows\\System32\\conhost.exe";
|
|
538
|
+
const tr = `"${conhost}" --headless "${spec.runtimeCmd}" "${spec.scriptPath}" --once`;
|
|
539
|
+
return ["/Create", "/TN", WIN_TASK_NAME, "/SC", "MINUTE", "/MO", String(spec.intervalMin), "/TR", tr, "/F"];
|
|
540
|
+
}
|
|
541
|
+
function buildSchtasksCreateArgs(spec) {
|
|
542
|
+
const tr = `"${spec.runtimeCmd}" "${spec.scriptPath}" --once`;
|
|
543
|
+
return ["/Create", "/TN", WIN_TASK_NAME, "/SC", "MINUTE", "/MO", String(spec.intervalMin), "/TR", tr, "/F"];
|
|
544
|
+
}
|
|
545
|
+
function buildSchtasksDeleteArgs() {
|
|
546
|
+
return ["/Delete", "/TN", WIN_TASK_NAME, "/F"];
|
|
547
|
+
}
|
|
548
|
+
function buildSystemdService(spec) {
|
|
549
|
+
return [
|
|
550
|
+
"[Unit]",
|
|
551
|
+
"Description=OpenCode QQBot watchdog (plugin-managed)",
|
|
552
|
+
"After=default.target",
|
|
553
|
+
"",
|
|
554
|
+
"[Service]",
|
|
555
|
+
"Type=oneshot",
|
|
556
|
+
`ExecStart="${spec.runtimeCmd}" "${spec.scriptPath}" --once`,
|
|
557
|
+
""
|
|
558
|
+
].join(`
|
|
559
|
+
`);
|
|
560
|
+
}
|
|
561
|
+
function buildSystemdTimer(intervalMin) {
|
|
562
|
+
return [
|
|
563
|
+
"[Unit]",
|
|
564
|
+
"Description=OpenCode QQBot watchdog timer",
|
|
565
|
+
"",
|
|
566
|
+
"[Timer]",
|
|
567
|
+
"OnBootSec=2min",
|
|
568
|
+
`OnUnitActiveSec=${intervalMin}min`,
|
|
569
|
+
`Unit=${SYSTEMD_UNIT}.service`,
|
|
570
|
+
"",
|
|
571
|
+
"[Install]",
|
|
572
|
+
"WantedBy=timers.target",
|
|
573
|
+
""
|
|
574
|
+
].join(`
|
|
575
|
+
`);
|
|
576
|
+
}
|
|
577
|
+
function buildLaunchdPlist(spec) {
|
|
578
|
+
const esc = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
579
|
+
return [
|
|
580
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
581
|
+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
582
|
+
'<plist version="1.0">',
|
|
583
|
+
"<dict>",
|
|
584
|
+
" <key>Label</key>",
|
|
585
|
+
` <string>${LAUNCHD_LABEL}</string>`,
|
|
586
|
+
" <key>ProgramArguments</key>",
|
|
587
|
+
" <array>",
|
|
588
|
+
` <string>${esc(spec.runtimeCmd)}</string>`,
|
|
589
|
+
` <string>${esc(spec.scriptPath)}</string>`,
|
|
590
|
+
" <string>--once</string>",
|
|
591
|
+
" </array>",
|
|
592
|
+
" <key>StartInterval</key>",
|
|
593
|
+
` <integer>${spec.intervalMin * 60}</integer>`,
|
|
594
|
+
" <key>RunAtLoad</key>",
|
|
595
|
+
" <true/>",
|
|
596
|
+
"</dict>",
|
|
597
|
+
"</plist>",
|
|
598
|
+
""
|
|
599
|
+
].join(`
|
|
600
|
+
`);
|
|
601
|
+
}
|
|
602
|
+
function systemdDir() {
|
|
603
|
+
return join4(homedir4(), ".config", "systemd", "user");
|
|
604
|
+
}
|
|
605
|
+
function launchdPath() {
|
|
606
|
+
return join4(homedir4(), "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
|
|
607
|
+
}
|
|
608
|
+
function registeredForm(platform = process.platform) {
|
|
609
|
+
if (platform !== "win32")
|
|
610
|
+
return "unknown";
|
|
611
|
+
const q = run("schtasks", ["/Query", "/TN", WIN_TASK_NAME, "/XML"]);
|
|
612
|
+
if (!q.ok)
|
|
613
|
+
return "unknown";
|
|
614
|
+
if (/<LogonType>S4U<\/LogonType>/.test(q.detail))
|
|
615
|
+
return "s4u";
|
|
616
|
+
if (q.detail.includes("--headless") && /<Command>[^<]*conhost\.exe/i.test(q.detail))
|
|
617
|
+
return "conhost";
|
|
618
|
+
return "interactive";
|
|
619
|
+
}
|
|
620
|
+
var FORM_LABEL = {
|
|
621
|
+
s4u: "S4U(非交互会话,tick 零窗口)",
|
|
622
|
+
conhost: "conhost --headless(隐藏控制台,需已登录会话)",
|
|
623
|
+
interactive: "Interactive(可能闪窗)",
|
|
624
|
+
unknown: "未知形态"
|
|
625
|
+
};
|
|
626
|
+
function serviceInstall(spec, platform = process.platform) {
|
|
627
|
+
if (platform === "win32") {
|
|
628
|
+
const xmlPath = join4(tmpdir(), `openqq-watchdog-task-${process.pid}.xml`);
|
|
629
|
+
try {
|
|
630
|
+
writeFileSync2(xmlPath, Buffer.concat([
|
|
631
|
+
new Uint8Array([255, 254]),
|
|
632
|
+
Buffer.from(buildSchtasksTaskXml(spec), "utf-16le")
|
|
633
|
+
]));
|
|
634
|
+
const res = run("schtasks", buildSchtasksXmlArgs(xmlPath));
|
|
635
|
+
if (res.ok) {
|
|
636
|
+
return { ok: true, detail: `${res.detail}
|
|
637
|
+
注册形态: ${FORM_LABEL.s4u}` };
|
|
638
|
+
}
|
|
639
|
+
const xmlErr = res.detail;
|
|
640
|
+
rmSync(xmlPath, { force: true });
|
|
641
|
+
const conhostRes = run("schtasks", buildSchtasksConhostArgs(spec));
|
|
642
|
+
if (conhostRes.ok) {
|
|
643
|
+
return { ok: true, detail: `${conhostRes.detail}
|
|
644
|
+
注册形态: ${FORM_LABEL.conhost}
|
|
645
|
+
(S4U 注册失败,已回退 conhost --headless 梯队,schtasks 原始输出:${xmlErr})` };
|
|
646
|
+
}
|
|
647
|
+
const legacy = run("schtasks", buildSchtasksCreateArgs(spec));
|
|
648
|
+
return {
|
|
649
|
+
...legacy,
|
|
650
|
+
detail: `${legacy.detail}
|
|
651
|
+
(S4U 与 conhost --headless 梯队均失败,已回退 Interactive 形态;S4U 输出:${xmlErr} | conhost 输出:${conhostRes.detail})`
|
|
652
|
+
};
|
|
653
|
+
} finally {
|
|
654
|
+
try {
|
|
655
|
+
rmSync(xmlPath, { force: true });
|
|
656
|
+
} catch {}
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
if (platform === "linux") {
|
|
660
|
+
const dir = systemdDir();
|
|
661
|
+
mkdirSync(dir, { recursive: true });
|
|
662
|
+
writeFileSync2(join4(dir, `${SYSTEMD_UNIT}.service`), buildSystemdService(spec));
|
|
663
|
+
writeFileSync2(join4(dir, `${SYSTEMD_UNIT}.timer`), buildSystemdTimer(spec.intervalMin));
|
|
664
|
+
const reload = run("systemctl", ["--user", "daemon-reload"]);
|
|
665
|
+
if (!reload.ok)
|
|
666
|
+
return reload;
|
|
667
|
+
const enable = run("systemctl", ["--user", "enable", "--now", `${SYSTEMD_UNIT}.timer`]);
|
|
668
|
+
return {
|
|
669
|
+
ok: enable.ok,
|
|
670
|
+
detail: `${enable.detail}
|
|
671
|
+
提示:无图形会话时需 loginctl enable-linger $USER 才能常驻`
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
if (platform === "darwin") {
|
|
675
|
+
const path = launchdPath();
|
|
676
|
+
mkdirSync(join4(homedir4(), "Library", "LaunchAgents"), { recursive: true });
|
|
677
|
+
writeFileSync2(path, buildLaunchdPlist(spec));
|
|
678
|
+
return run("launchctl", ["load", "-w", path]);
|
|
679
|
+
}
|
|
680
|
+
return { ok: false, detail: `不支持的平台:${platform}` };
|
|
681
|
+
}
|
|
682
|
+
function serviceUninstall(platform = process.platform) {
|
|
683
|
+
if (platform === "win32")
|
|
684
|
+
return run("schtasks", buildSchtasksDeleteArgs());
|
|
685
|
+
if (platform === "linux") {
|
|
686
|
+
run("systemctl", ["--user", "disable", "--now", `${SYSTEMD_UNIT}.timer`]);
|
|
687
|
+
rmSync(join4(systemdDir(), `${SYSTEMD_UNIT}.timer`), { force: true });
|
|
688
|
+
rmSync(join4(systemdDir(), `${SYSTEMD_UNIT}.service`), { force: true });
|
|
689
|
+
return run("systemctl", ["--user", "daemon-reload"]);
|
|
690
|
+
}
|
|
691
|
+
if (platform === "darwin") {
|
|
692
|
+
const path = launchdPath();
|
|
693
|
+
const res = run("launchctl", ["unload", "-w", path]);
|
|
694
|
+
rmSync(path, { force: true });
|
|
695
|
+
return res;
|
|
696
|
+
}
|
|
697
|
+
return { ok: false, detail: `不支持的平台:${platform}` };
|
|
698
|
+
}
|
|
699
|
+
function serviceStatus(platform = process.platform) {
|
|
700
|
+
if (platform === "win32") {
|
|
701
|
+
const q = run("schtasks", ["/Query", "/TN", WIN_TASK_NAME]);
|
|
702
|
+
const form = q.ok ? `注册形态: ${FORM_LABEL[registeredForm(platform)]}` : "任务未注册";
|
|
703
|
+
return { ...q, detail: `${q.detail}
|
|
704
|
+
${form}` };
|
|
705
|
+
}
|
|
706
|
+
if (platform === "linux") {
|
|
707
|
+
const exists = existsSync3(join4(systemdDir(), `${SYSTEMD_UNIT}.timer`));
|
|
708
|
+
const active = run("systemctl", ["--user", "is-active", `${SYSTEMD_UNIT}.timer`]);
|
|
709
|
+
return { ok: exists && active.ok, detail: `unit 文件存在=${exists}
|
|
710
|
+
${active.detail}` };
|
|
711
|
+
}
|
|
712
|
+
if (platform === "darwin") {
|
|
713
|
+
const path = launchdPath();
|
|
714
|
+
return { ok: existsSync3(path), detail: `${path} 存在=${existsSync3(path)}
|
|
715
|
+
${run("launchctl", ["list", LAUNCHD_LABEL]).detail}` };
|
|
716
|
+
}
|
|
717
|
+
return { ok: false, detail: `不支持的平台:${platform}` };
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
// src/cli/openqq-main.ts
|
|
721
|
+
var DEFAULT_INTERVAL_MIN = 10;
|
|
722
|
+
function sibling(name) {
|
|
723
|
+
const here = dirname3(fileURLToPath2(import.meta.url));
|
|
724
|
+
const candidates = [join5(here, name), join5(here, "..", "dist", name)];
|
|
725
|
+
return candidates.find((p) => existsSync4(p)) ?? candidates[0];
|
|
726
|
+
}
|
|
727
|
+
function runtimeCommand() {
|
|
728
|
+
const runtime = resolveRuntime();
|
|
729
|
+
if (runtime === "bun")
|
|
730
|
+
return resolveBunCommand() ?? throwNoRuntime("bun");
|
|
731
|
+
if (runtime === "node")
|
|
732
|
+
return locateOnPath("node") ?? throwNoRuntime("node");
|
|
733
|
+
throw new Error("未找到 bun/node 运行时");
|
|
734
|
+
}
|
|
735
|
+
function throwNoRuntime(kind) {
|
|
736
|
+
throw new Error(`未找到 ${kind} 全路径可执行体——注册动作需要全路径命令(静默红线)`);
|
|
737
|
+
}
|
|
738
|
+
function printResult(label, r) {
|
|
739
|
+
console.log(`[${label}] ${r.ok ? "OK" : "FAIL"}
|
|
740
|
+
${r.detail}`);
|
|
741
|
+
process.exitCode = r.ok ? 0 : 1;
|
|
742
|
+
}
|
|
743
|
+
function parseFlag(argv, name) {
|
|
744
|
+
const i = argv.indexOf(name);
|
|
745
|
+
return i >= 0 ? argv[i + 1] ?? "" : null;
|
|
746
|
+
}
|
|
747
|
+
async function main() {
|
|
748
|
+
const [cmd, sub] = process.argv.slice(2);
|
|
749
|
+
if (cmd === "restart") {
|
|
750
|
+
const force = process.argv.includes("--force");
|
|
751
|
+
const timeoutMin = Number(parseFlag(process.argv.slice(2), "--timeout-min"));
|
|
752
|
+
const res = await restartBot({
|
|
753
|
+
force,
|
|
754
|
+
timeoutMs: Number.isFinite(timeoutMin) && timeoutMin > 0 ? timeoutMin * 60000 : undefined,
|
|
755
|
+
spawnFromUrl: import.meta.url,
|
|
756
|
+
log: (line) => console.log(line)
|
|
757
|
+
});
|
|
758
|
+
console.log(`[restart] ${res.action}(${res.reason})killed=${res.killedPid ?? "-"} spawned=${res.spawnedPid ?? "-"}`);
|
|
759
|
+
process.exitCode = res.action === "restarted" ? 0 : 2;
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
if (cmd === "service") {
|
|
763
|
+
const spec = {
|
|
764
|
+
runtimeCmd: runtimeCommand(),
|
|
765
|
+
scriptPath: sibling("openqq-watchdog.js"),
|
|
766
|
+
intervalMin: DEFAULT_INTERVAL_MIN
|
|
767
|
+
};
|
|
768
|
+
if (sub === "install")
|
|
769
|
+
return printResult("service install", serviceInstall(spec));
|
|
770
|
+
if (sub === "uninstall")
|
|
771
|
+
return printResult("service uninstall", serviceUninstall());
|
|
772
|
+
if (sub === "status") {
|
|
773
|
+
const r = serviceStatus();
|
|
774
|
+
return printResult("service status", {
|
|
775
|
+
ok: r.ok,
|
|
776
|
+
detail: `runtime=${spec.runtimeCmd}
|
|
777
|
+
script=${spec.scriptPath}
|
|
778
|
+
${r.detail}`
|
|
779
|
+
});
|
|
780
|
+
}
|
|
781
|
+
console.error("用法:openqq service install|uninstall|status");
|
|
782
|
+
process.exitCode = 2;
|
|
783
|
+
return;
|
|
784
|
+
}
|
|
785
|
+
console.error("用法:openqq-cli restart [--force] [--timeout-min N] | service install|uninstall|status");
|
|
786
|
+
process.exitCode = 2;
|
|
787
|
+
}
|
|
788
|
+
main().catch((error) => {
|
|
789
|
+
console.error("[openqq-cli] 执行失败:", error instanceof Error ? error.message : error);
|
|
790
|
+
process.exit(1);
|
|
791
|
+
});
|