@linjz/opencode-qqbot 0.3.15 → 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.
Files changed (61) hide show
  1. package/README.md +303 -229
  2. package/README.zh-CN.md +313 -0
  3. package/bin/openqq.js +13 -0
  4. package/dist/notify-cli.js +92 -26
  5. package/dist/opencode-qqbot-plugin.js +1201 -67
  6. package/dist/openqq-bot.js +3963 -893
  7. package/dist/openqq-cli.js +980 -0
  8. package/dist/openqq-watchdog.js +1326 -0
  9. package/package.json +8 -5
  10. package/src/bridge.ts +1599 -150
  11. package/src/cli/notify.ts +170 -158
  12. package/src/cli/openqq-main.ts +95 -0
  13. package/src/cli/service-main.ts +302 -0
  14. package/src/cli/watchdog-main.ts +92 -0
  15. package/src/commands.ts +670 -554
  16. package/src/config.ts +122 -3
  17. package/src/core/bot-config.ts +66 -0
  18. package/src/core/bot-control.ts +166 -0
  19. package/src/core/bot-launcher.ts +110 -15
  20. package/src/core/card-approval.ts +20 -9
  21. package/src/core/cron-reminders.ts +84 -0
  22. package/src/core/delivery.ts +145 -54
  23. package/src/core/discovery.ts +207 -151
  24. package/src/core/error-rescue.ts +1 -1
  25. package/src/core/file-log.ts +50 -9
  26. package/src/core/form-bridge.ts +14 -5
  27. package/src/core/form-journal.ts +4 -4
  28. package/src/core/gateway-state.ts +3 -3
  29. package/src/core/inflight-journal.ts +215 -36
  30. package/src/core/instance-lock.ts +42 -3
  31. package/src/core/linkwatch.ts +3 -4
  32. package/src/core/log-rotate.ts +91 -0
  33. package/src/core/markdown.ts +117 -0
  34. package/src/core/message-queue.ts +242 -91
  35. package/src/core/mirror.ts +228 -182
  36. package/src/core/notices.ts +62 -0
  37. package/src/core/notify-sink.ts +93 -96
  38. package/src/core/outbound-sanitize.ts +29 -0
  39. package/src/core/outbox.ts +10 -9
  40. package/src/core/permission.ts +634 -303
  41. package/src/core/question-form.ts +230 -0
  42. package/src/core/queue-view.ts +662 -0
  43. package/src/core/send-media.ts +61 -2
  44. package/src/core/start-error.ts +26 -0
  45. package/src/core/storage.ts +34 -0
  46. package/src/core/stt.ts +55 -0
  47. package/src/core/supervisor-election.ts +53 -0
  48. package/src/core/watchdog.ts +670 -0
  49. package/src/core/zombie-reaper.ts +127 -0
  50. package/src/index.ts +262 -162
  51. package/src/opencode/client.ts +237 -27
  52. package/src/opencode/eventstream.ts +94 -12
  53. package/src/opencode/history.ts +4 -2
  54. package/src/opencode/mirror.ts +25 -5
  55. package/src/opencode/sessions.ts +135 -37
  56. package/src/plugin-entry.ts +139 -115
  57. package/src/qq/api.ts +165 -61
  58. package/src/qq/gateway.ts +114 -16
  59. package/src/qq/media.ts +21 -0
  60. package/src/qq/sender.ts +79 -18
  61. package/src/qq/types.ts +7 -0
@@ -0,0 +1,980 @@
1
+ // src/cli/openqq-main.ts
2
+ import { existsSync as existsSync6 } from "fs";
3
+ import { dirname as dirname4, join as join6 } from "path";
4
+ import { fileURLToPath as fileURLToPath2 } from "url";
5
+
6
+ // src/core/bot-control.ts
7
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
8
+ import { dirname as dirname3, join as join4 } 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", "openqq.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 { existsSync as existsSync3, readFileSync as readFileSync3, statSync as statSync4, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "fs";
161
+ import { dirname as dirname2, join as join3 } from "path";
162
+ import { homedir as homedir2 } from "os";
163
+
164
+ // src/core/log-rotate.ts
165
+ import { existsSync as existsSync2, renameSync, rmSync, statSync as statSync2 } from "fs";
166
+ var MB = 1024 * 1024;
167
+ var num = (v, d) => {
168
+ const n = Number(v);
169
+ return Number.isFinite(n) && n > 0 ? n : d;
170
+ };
171
+ function logLimitsFromEnv(env = process.env) {
172
+ return {
173
+ maxBytes: num(env.QQ_LOG_MAX_MB, 20) * MB,
174
+ keepBackups: Math.floor(num(env.QQ_LOG_KEEP, 4)),
175
+ totalBudgetBytes: num(env.QQ_LOG_TOTAL_MB, 100) * MB
176
+ };
177
+ }
178
+ function rotateLogIfNeeded(logPath, limits = logLimitsFromEnv()) {
179
+ try {
180
+ if (!existsSync2(logPath) || statSync2(logPath).size <= limits.maxBytes)
181
+ return false;
182
+ try {
183
+ rmSync(`${logPath}.${limits.keepBackups}`, { force: true });
184
+ } catch {}
185
+ for (let i = limits.keepBackups - 1;i >= 1; i--) {
186
+ const from = `${logPath}.${i}`;
187
+ if (!existsSync2(from))
188
+ continue;
189
+ try {
190
+ renameSync(from, `${logPath}.${i + 1}`);
191
+ } catch {}
192
+ }
193
+ try {
194
+ renameSync(logPath, `${logPath}.1`);
195
+ } catch {
196
+ return false;
197
+ }
198
+ return true;
199
+ } catch {
200
+ return false;
201
+ }
202
+ }
203
+ function enforceLogBudget(logPath, limits = logLimitsFromEnv()) {
204
+ try {
205
+ const sizes = new Map;
206
+ let total = 0;
207
+ for (let i = 0;i <= 64; i++) {
208
+ const p = i === 0 ? logPath : `${logPath}.${i}`;
209
+ if (!existsSync2(p))
210
+ break;
211
+ const s = statSync2(p).size;
212
+ sizes.set(i, s);
213
+ total += s;
214
+ }
215
+ for (let i = limits.keepBackups;i >= 1 && total > limits.totalBudgetBytes; i--) {
216
+ const s = sizes.get(i);
217
+ if (s === undefined)
218
+ continue;
219
+ try {
220
+ rmSync(`${logPath}.${i}`, { force: true });
221
+ total -= s;
222
+ } catch {}
223
+ }
224
+ } catch {}
225
+ }
226
+
227
+ // src/core/instance-lock.ts
228
+ import { openSync, readFileSync as readFileSync2, readdirSync, writeFileSync, closeSync, unlinkSync, statSync as statSync3, utimesSync, mkdirSync } from "fs";
229
+ import { join as join2 } from "path";
230
+ function releaseLocksOfPid(pid, dir) {
231
+ let names;
232
+ try {
233
+ names = readdirSync(dir);
234
+ } catch {
235
+ return [];
236
+ }
237
+ const cleared = [];
238
+ for (const name of names) {
239
+ if (!/^openqq-.+\.lock$/.test(name))
240
+ continue;
241
+ const p = join2(dir, name);
242
+ try {
243
+ const holder = JSON.parse(readFileSync2(p, "utf-8"));
244
+ if (holder.pid === pid) {
245
+ unlinkSync(p);
246
+ cleared.push(p);
247
+ }
248
+ } catch {}
249
+ }
250
+ return cleared;
251
+ }
252
+
253
+ // src/core/watchdog.ts
254
+ var HEARTBEAT_STALE_MS = 5 * 60000;
255
+ function botWatchdogPaths(appId) {
256
+ const dir = join3(homedir2(), ".openqq");
257
+ return { lockPath: join3(dir, `openqq-${appId}.lock`), heartbeatPath: join3(dir, "heartbeat") };
258
+ }
259
+ function isPidAlive(pid) {
260
+ if (!Number.isInteger(pid) || pid <= 0)
261
+ return false;
262
+ try {
263
+ process.kill(pid, 0);
264
+ return true;
265
+ } catch (error) {
266
+ return error.code === "EPERM";
267
+ }
268
+ }
269
+ function ageOf(path, now) {
270
+ try {
271
+ return Math.max(0, now - statSync4(path).mtimeMs);
272
+ } catch {
273
+ return null;
274
+ }
275
+ }
276
+ function readBotHealth(paths, now = Date.now()) {
277
+ const lockAgeMs = ageOf(paths.lockPath, now);
278
+ let lockPid = null;
279
+ if (lockAgeMs !== null) {
280
+ try {
281
+ const raw = JSON.parse(readFileSync3(paths.lockPath, "utf-8"));
282
+ if (typeof raw.pid === "number" && Number.isInteger(raw.pid))
283
+ lockPid = raw.pid;
284
+ } catch {}
285
+ }
286
+ return {
287
+ lockPid,
288
+ lockAgeMs,
289
+ pidAlive: lockPid === null ? null : isPidAlive(lockPid),
290
+ heartbeatAgeMs: ageOf(paths.heartbeatPath, now)
291
+ };
292
+ }
293
+ function appendWatchdogLog(line) {
294
+ try {
295
+ const logPath = join3(homedir2(), ".openqq", "openqq.log");
296
+ const limits = logLimitsFromEnv();
297
+ if (existsSync3(logPath) && statSync4(logPath).size > limits.maxBytes) {
298
+ if (rotateLogIfNeeded(logPath, limits))
299
+ enforceLogBudget(logPath, limits);
300
+ }
301
+ writeFileSync2(logPath, `${new Date().toISOString()} ${line}
302
+ `, { flag: "a" });
303
+ } catch {}
304
+ }
305
+ function appendKillLog(entry, logPath = join3(homedir2(), ".openqq", "kills.log")) {
306
+ try {
307
+ writeFileSync2(logPath, `${JSON.stringify(entry)}
308
+ `, { flag: "a" });
309
+ const limits = logLimitsFromEnv();
310
+ if (existsSync3(logPath) && statSync4(logPath).size > limits.maxBytes) {
311
+ if (rotateLogIfNeeded(logPath, limits))
312
+ enforceLogBudget(logPath, limits);
313
+ }
314
+ } catch {}
315
+ }
316
+ var DEFAULT_SUPERVISOR_POLICY = {
317
+ cooldownMs: 2 * 60000,
318
+ maxRestarts: 3,
319
+ windowMs: 15 * 60000,
320
+ graceMs: 8000,
321
+ claimTtlMs: 90000
322
+ };
323
+ function decideSupervise(health, state, now, policy = DEFAULT_SUPERVISOR_POLICY) {
324
+ const staleHeartbeat = health.heartbeatAgeMs !== null && health.heartbeatAgeMs > HEARTBEAT_STALE_MS;
325
+ const needsRestart = health.lockPid === null || health.pidAlive === false || staleHeartbeat;
326
+ if (!needsRestart)
327
+ return { kind: "ok" };
328
+ const windowStart = now - policy.windowMs;
329
+ const recentRestarts = state.restartLog.filter((t) => t > windowStart).length;
330
+ if (recentRestarts >= policy.maxRestarts)
331
+ return { kind: "give-up", restarts: recentRestarts };
332
+ const last = state.restartLog[state.restartLog.length - 1] ?? null;
333
+ if (last !== null && now - last < policy.cooldownMs)
334
+ return { kind: "cooldown", untilMs: last + policy.cooldownMs };
335
+ if (health.lockPid !== null && health.pidAlive !== false && staleHeartbeat) {
336
+ return {
337
+ kind: "grace-kill-spawn",
338
+ killPid: health.lockPid,
339
+ reason: `心跳陈旧 ${Math.round((health.heartbeatAgeMs ?? 0) / 60000)} 分钟(进程活但事件循环无进展)`
340
+ };
341
+ }
342
+ return { kind: "spawn", reason: health.lockPid === null ? "无实例锁(bot 未运行)" : "锁定进程已退出" };
343
+ }
344
+ var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
345
+ var defaultSupervisorKill = (pid, signal) => {
346
+ try {
347
+ process.kill(pid, signal);
348
+ } catch {}
349
+ };
350
+ function readJson(path, fallback) {
351
+ try {
352
+ return { ...fallback, ...JSON.parse(readFileSync3(path, "utf-8")) };
353
+ } catch {
354
+ return fallback;
355
+ }
356
+ }
357
+ async function superviseOnce(deps) {
358
+ const policy = deps.policy ?? DEFAULT_SUPERVISOR_POLICY;
359
+ const now = deps.now?.() ?? Date.now();
360
+ const log = deps.log ?? (() => {});
361
+ const sleep = deps.sleep ?? defaultSleep;
362
+ const kill = deps.kill ?? defaultSupervisorKill;
363
+ const isAlive = deps.isAlive ?? isPidAlive;
364
+ const statePath = deps.statePath ?? join3(homedir2(), ".openqq", "supervisor.json");
365
+ const claimPath = deps.claimPath ?? join3(homedir2(), ".openqq", "supervisor.lock");
366
+ const audit = (line) => {
367
+ if (deps.auditLogPath) {
368
+ try {
369
+ writeFileSync2(deps.auditLogPath, `${new Date().toISOString()} ${line}
370
+ `, { flag: "a" });
371
+ return;
372
+ } catch {}
373
+ }
374
+ appendWatchdogLog(line);
375
+ };
376
+ const claim = readJson(claimPath, { pid: 0, ts: 0 });
377
+ if (claim.ts && now - claim.ts < policy.claimTtlMs && claim.pid !== process.pid) {
378
+ return { action: "yield", detail: `监督者 pid=${claim.pid} 持锁中`, killedPid: null, spawnedPid: null };
379
+ }
380
+ try {
381
+ writeFileSync2(claimPath, JSON.stringify({ pid: process.pid, ts: now }));
382
+ } catch {
383
+ return { action: "yield", detail: "认领锁不可写", killedPid: null, spawnedPid: null };
384
+ }
385
+ const release = () => {
386
+ try {
387
+ writeFileSync2(claimPath, JSON.stringify({ pid: 0, ts: 0 }));
388
+ } catch {}
389
+ };
390
+ try {
391
+ const health = readBotHealth(deps.paths, now);
392
+ const state = readJson(statePath, { restartLog: [] });
393
+ let action = decideSupervise(health, state, now, policy);
394
+ if (deps.request === "manual-restart" && action.kind === "ok") {
395
+ const windowStart = now - policy.windowMs;
396
+ const recentRestarts = state.restartLog.filter((t) => t > windowStart).length;
397
+ if (recentRestarts >= policy.maxRestarts) {
398
+ return {
399
+ action: "give-up",
400
+ detail: `15 分钟内已重启 ${recentRestarts} 次(监督强度上限),人工重启亦被拦截,请排查根因`,
401
+ killedPid: null,
402
+ spawnedPid: null
403
+ };
404
+ }
405
+ const last = state.restartLog[state.restartLog.length - 1] ?? null;
406
+ if (last !== null && now - last < policy.cooldownMs) {
407
+ return { action: "cooldown", detail: `距上次重启不足 ${Math.round(policy.cooldownMs / 1000)}s(冷却期),人工重启跳过`, killedPid: null, spawnedPid: null };
408
+ }
409
+ action = health.lockPid !== null && health.pidAlive !== false ? { kind: "grace-kill-spawn", killPid: health.lockPid, reason: "人工请求重启(openqq restart)" } : { kind: "spawn", reason: "人工请求重启(bot 未运行,直接拉起)" };
410
+ }
411
+ if (action.kind === "ok")
412
+ return { action: "ok", detail: "健康", killedPid: null, spawnedPid: null };
413
+ if (action.kind === "cooldown") {
414
+ log(`[supervisor] 冷却中(上次重启 ${Math.round((now - (action.untilMs - policy.cooldownMs)) / 1000)}s 前),本轮跳过`);
415
+ return { action: "cooldown", detail: "冷却跳过", killedPid: null, spawnedPid: null };
416
+ }
417
+ if (action.kind === "yield") {
418
+ return { action: "yield", detail: action.reason, killedPid: null, spawnedPid: null };
419
+ }
420
+ if (action.kind === "give-up") {
421
+ const message = `⚠️ QQBot 看门狗已达重启强度上限:${action.restarts} 次/${Math.round(policy.windowMs / 60000)} 分钟仍不健康(同因反复死亡)。降频重试继续——巡检不会停,强度窗口滑动后自动恢复,引擎/环境自愈即自行好转;若持续收到此告警,请检查 ~/.openqq/openqq.log(bot 与看门狗统一日志)。`;
422
+ audit(`give-up:${message}`);
423
+ log(`[supervisor] give-up:${action.restarts} 次重启仍异常,降频重试继续并上报(不再永动猛拉)`);
424
+ const lastAlert = state.alertedAt ?? 0;
425
+ if (now - lastAlert > 30 * 60000) {
426
+ try {
427
+ deps.alert?.(message);
428
+ state.alertedAt = now;
429
+ writeFileSync2(statePath, JSON.stringify(state));
430
+ } catch {}
431
+ }
432
+ return { action: "give-up", detail: message, killedPid: null, spawnedPid: null };
433
+ }
434
+ let killedPid = null;
435
+ if (action.kind === "grace-kill-spawn" && action.killPid !== process.pid) {
436
+ const pid = action.killPid;
437
+ if (deps.request !== "manual-restart") {
438
+ await sleep(300);
439
+ const recheck = readBotHealth(deps.paths, Date.now());
440
+ const recheckFresh = recheck.heartbeatAgeMs !== null && recheck.heartbeatAgeMs <= HEARTBEAT_STALE_MS;
441
+ if (recheck.pidAlive !== false && recheckFresh) {
442
+ const ageSec = Math.round((recheck.heartbeatAgeMs ?? 0) / 1000);
443
+ audit(`杀前复核改判 ok:pid=${pid} 心跳已恢复(年龄 ${ageSec}s),放弃误杀`);
444
+ log(`[supervisor] 杀前复核改判 ok:心跳已恢复(${ageSec}s),放弃杀 pid=${pid}`);
445
+ return { action: "ok", detail: `杀前复核:心跳已恢复,放弃误杀 pid=${pid}`, killedPid: null, spawnedPid: null };
446
+ }
447
+ }
448
+ kill(pid, "SIGTERM");
449
+ const deadline = now + policy.graceMs;
450
+ let alive = isAlive(pid);
451
+ while (alive && Date.now() < deadline) {
452
+ await sleep(250);
453
+ alive = isAlive(pid);
454
+ }
455
+ if (alive) {
456
+ kill(pid, "SIGKILL");
457
+ const hardDeadline = Date.now() + 3000;
458
+ while (alive && Date.now() < hardDeadline) {
459
+ await sleep(250);
460
+ alive = isAlive(pid);
461
+ }
462
+ }
463
+ if (alive) {
464
+ audit(`give-up-kill:pid=${pid} 无法终止(权限/系统级),本次不拉起`);
465
+ return { action: "give-up", detail: `pid=${pid} 无法终止`, killedPid: null, spawnedPid: null };
466
+ }
467
+ killedPid = pid;
468
+ }
469
+ try {
470
+ const locksDir = dirname2(deps.paths.lockPath);
471
+ let cleared = [];
472
+ if (killedPid !== null) {
473
+ cleared = releaseLocksOfPid(killedPid, locksDir);
474
+ } else if (health.pidAlive === false && health.lockPid !== null) {
475
+ cleared = releaseLocksOfPid(health.lockPid, locksDir);
476
+ }
477
+ if (existsSync3(deps.paths.lockPath)) {
478
+ try {
479
+ unlinkSync2(deps.paths.lockPath);
480
+ if (!cleared.includes(deps.paths.lockPath))
481
+ cleared.push(deps.paths.lockPath);
482
+ } catch {}
483
+ }
484
+ if (cleared.length > 0)
485
+ audit(`清锁:${cleared.join("、")}(${action.reason})`);
486
+ } catch {}
487
+ const spawnedPid = deps.spawn();
488
+ state.restartLog.push(Date.now());
489
+ state.restartLog = state.restartLog.filter((t) => t > Date.now() - policy.windowMs * 2);
490
+ try {
491
+ writeFileSync2(statePath, JSON.stringify(state));
492
+ } catch {
493
+ log("[supervisor] 强度账落盘失败(不影响本次拉起)");
494
+ }
495
+ let livenessVerdict = "alive";
496
+ let respawnPid = null;
497
+ if (deps.livenessCheck !== false) {
498
+ const graceWaitMs = 1e4;
499
+ await sleep(graceWaitMs);
500
+ const liveness = readBotHealth(deps.paths, Date.now());
501
+ if (!isPidAlive(spawnedPid) || liveness.lockPid === null) {
502
+ livenessVerdict = `dead-after-spawn(10s 复核:进程${isPidAlive(spawnedPid) ? "在但锁未建立" : "已退出"})`;
503
+ audit(`二次追击:拉起 pid=${spawnedPid} 失败(${livenessVerdict}),立即重拉`);
504
+ try {
505
+ const locksDir2 = dirname2(deps.paths.lockPath);
506
+ let cleared2 = [];
507
+ if (!isPidAlive(spawnedPid) && existsSync3(deps.paths.lockPath)) {
508
+ cleared2 = releaseLocksOfPid(spawnedPid, locksDir2);
509
+ }
510
+ if (existsSync3(deps.paths.lockPath)) {
511
+ try {
512
+ unlinkSync2(deps.paths.lockPath);
513
+ if (!cleared2.includes(deps.paths.lockPath))
514
+ cleared2.push(deps.paths.lockPath);
515
+ } catch {}
516
+ }
517
+ if (cleared2.length > 0)
518
+ audit(`清锁:${cleared2.join("、")}(二次追击前清场)`);
519
+ } catch {}
520
+ respawnPid = deps.spawn();
521
+ await sleep(graceWaitMs);
522
+ const liveness2 = readBotHealth(deps.paths, Date.now());
523
+ if (!isPidAlive(respawnPid) || liveness2.lockPid === null) {
524
+ livenessVerdict += `;二次拉起 pid=${respawnPid} 仍失败——交下轮巡检接力(强度账 ${state.restartLog.length}/${policy.maxRestarts})`;
525
+ } else {
526
+ livenessVerdict += `;二次拉起 pid=${respawnPid} 成功`;
527
+ }
528
+ }
529
+ }
530
+ if (killedPid !== null || livenessVerdict !== "alive") {
531
+ appendKillLog({
532
+ kind: "decision",
533
+ reason: action.reason,
534
+ health: {
535
+ lockPid: health.lockPid,
536
+ pidAlive: health.pidAlive,
537
+ heartbeatAgeMs: health.heartbeatAgeMs,
538
+ lockAgeMs: health.lockAgeMs
539
+ },
540
+ killedPid,
541
+ killEscalation: killedPid !== null ? "TERM" : "n/a",
542
+ spawnedPid: respawnPid ?? spawnedPid,
543
+ restartIntensity: `${state.restartLog.length}/${policy.maxRestarts}`,
544
+ livenessVerdict: livenessVerdict !== "alive" ? livenessVerdict : "alive",
545
+ at: Date.now()
546
+ });
547
+ }
548
+ const detail = `${action.reason};${killedPid ? `已优雅停 pid=${killedPid};` : ""}已拉起 pid=${respawnPid ?? spawnedPid}${livenessVerdict !== "alive" ? `;${livenessVerdict}` : ""}`;
549
+ audit(killedPid ? `主动杀:${detail}` : `验尸拉新:${detail}`);
550
+ return { action: "restart", detail, killedPid, spawnedPid: respawnPid ?? spawnedPid };
551
+ } finally {
552
+ release();
553
+ }
554
+ }
555
+
556
+ // src/core/bot-control.ts
557
+ function resolveInstalledBotEntry(fromUrl, exists = existsSync4) {
558
+ const here = dirname3(fileURLToPath(fromUrl));
559
+ const candidates = [
560
+ join4(here, "openqq-bot.js"),
561
+ join4(here, "..", "dist", "openqq-bot.js"),
562
+ join4(here, "..", "src", "index.ts"),
563
+ join4(here, "..", "..", "src", "index.ts")
564
+ ];
565
+ for (const c of candidates)
566
+ if (exists(c))
567
+ return c;
568
+ return null;
569
+ }
570
+ function readAppId(envPath = join4(homedir3(), ".openqq", ".env")) {
571
+ let botsRaw = null;
572
+ try {
573
+ for (const line of readFileSync4(envPath, "utf-8").split(`
574
+ `)) {
575
+ const t = line.trim();
576
+ if (!t || t.startsWith("#"))
577
+ continue;
578
+ const eq = t.indexOf("=");
579
+ if (eq < 0)
580
+ continue;
581
+ const key = t.slice(0, eq).trim();
582
+ if (key === "QQ_APP_ID") {
583
+ const v = t.slice(eq + 1).trim();
584
+ if (v)
585
+ return v;
586
+ }
587
+ if (key === "QQ_BOTS")
588
+ botsRaw = t.slice(eq + 1).trim();
589
+ }
590
+ } catch {}
591
+ if (botsRaw) {
592
+ try {
593
+ const arr = JSON.parse(botsRaw);
594
+ const first = Array.isArray(arr) ? arr[0]?.appId : undefined;
595
+ if (typeof first === "string" && first)
596
+ return first;
597
+ } catch {}
598
+ }
599
+ return null;
600
+ }
601
+ function inflightPath() {
602
+ return join4(homedir3(), ".openqq", "inflight.json");
603
+ }
604
+ function countInflight(path = inflightPath()) {
605
+ try {
606
+ const raw = JSON.parse(readFileSync4(path, "utf-8"));
607
+ if (!Array.isArray(raw))
608
+ return 0;
609
+ return raw.filter((e) => e.state === "inflight").length;
610
+ } catch {
611
+ return 0;
612
+ }
613
+ }
614
+ async function waitUntilIdle(opts) {
615
+ const timeoutMs = opts?.timeoutMs ?? 60 * 60000;
616
+ const pollMs = opts?.pollMs ?? 1e4;
617
+ const started = Date.now();
618
+ for (;; ) {
619
+ const n = countInflight();
620
+ if (n === 0)
621
+ return true;
622
+ const elapsed = Date.now() - started;
623
+ if (elapsed >= timeoutMs)
624
+ return false;
625
+ opts?.onWait?.(n, elapsed);
626
+ await new Promise((r) => setTimeout(r, pollMs));
627
+ }
628
+ }
629
+ function startBot(fromUrl, log = () => {}) {
630
+ const entry = resolveInstalledBotEntry(fromUrl);
631
+ if (!entry)
632
+ throw new Error("未找到 bot 入口(dist/openqq-bot.js 或 src/index.ts)——安装不完整");
633
+ const runtime = resolveRuntime();
634
+ if (!runtime)
635
+ throw new Error("未找到 bun/node 运行时");
636
+ const plan = buildLaunchPlan(runtime, entry, botLogPath());
637
+ const pid = spawnBotDetached(plan);
638
+ log(`[bot-control] 已拉起 pid=${pid}(runtime=${runtime},entry=${entry})`);
639
+ return pid;
640
+ }
641
+ async function restartBot(opts) {
642
+ const log = opts.log ?? (() => {});
643
+ const appId = readAppId();
644
+ if (!appId)
645
+ throw new Error("缺少 ~/.openqq/.env 的角色凭据(QQ_APP_ID 或 QQ_BOTS 首角色),无法定位实例锁");
646
+ if (!opts.force) {
647
+ const idle = await waitUntilIdle({
648
+ timeoutMs: opts.timeoutMs,
649
+ onWait: (n, elapsed) => log(`[bot-control] 仍在途 ${n} 条(已等 ${Math.round(elapsed / 1000)}s),继续等待空闲`)
650
+ });
651
+ if (!idle) {
652
+ log("[bot-control] 等待空闲超时:本次不重启(需要时用 --force)");
653
+ return { action: "skipped", killedPid: null, spawnedPid: null, reason: "等待空闲超时" };
654
+ }
655
+ }
656
+ const r = await superviseOnce({
657
+ paths: botWatchdogPaths(appId),
658
+ request: "manual-restart",
659
+ spawn: () => startBot(opts.spawnFromUrl, log),
660
+ log
661
+ });
662
+ switch (r.action) {
663
+ case "restart":
664
+ return { action: "restarted", killedPid: r.killedPid, spawnedPid: r.spawnedPid, reason: opts.force ? "force(经监督矩阵)" : "idle(经监督矩阵)" };
665
+ case "cooldown":
666
+ return { action: "skipped", killedPid: null, spawnedPid: null, reason: `监督矩阵冷却跳过:${r.detail}` };
667
+ case "give-up":
668
+ return { action: "skipped", killedPid: null, spawnedPid: null, reason: `监督矩阵 give-up:${r.detail}` };
669
+ case "yield":
670
+ return { action: "skipped", killedPid: null, spawnedPid: null, reason: `认领互斥:${r.detail}` };
671
+ default:
672
+ return { action: "skipped", killedPid: null, spawnedPid: null, reason: `无需动作:${r.detail}` };
673
+ }
674
+ }
675
+
676
+ // src/cli/service-main.ts
677
+ import { spawnSync as spawnSync2 } from "child_process";
678
+ import { existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync5, rmSync as rmSync2, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
679
+ import { homedir as homedir4, tmpdir } from "os";
680
+ import { join as join5 } from "path";
681
+ var WIN_TASK_NAME = "OpenQQBotWatchdog";
682
+ var SYSTEMD_UNIT = "openqq-watchdog";
683
+ var LAUNCHD_LABEL = "com.linjp.opencode-qqbot.watchdog";
684
+ function run(cmd, args) {
685
+ try {
686
+ const r = spawnSync2(cmd, args, { encoding: "utf-8", windowsHide: true });
687
+ const detail = `${cmd} ${args.join(" ")}
688
+ ${(r.stdout ?? "").trim()}${(r.stderr ?? "").trim() ? `
689
+ ${r.stderr.trim()}` : ""}`;
690
+ return { ok: r.status === 0, detail };
691
+ } catch (error) {
692
+ return { ok: false, detail: `执行失败:${error instanceof Error ? error.message : String(error)}` };
693
+ }
694
+ }
695
+ var escXml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
696
+ function buildSchtasksTaskXml(spec, now = new Date) {
697
+ const user = escXml(process.env.USERNAME ?? "SYSTEM");
698
+ const trigger = `<TimeTrigger><StartBoundary>${now.toISOString()}</StartBoundary>` + `<Repetition><Interval>PT${spec.intervalMin}M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition>` + `<Enabled>true</Enabled></TimeTrigger>`;
699
+ return [
700
+ '<?xml version="1.0" encoding="UTF-16"?>',
701
+ '<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',
702
+ `<RegistrationInfo><Author>${user}</Author><Description>OpenCode QQBot watchdog (plugin-managed, silent)</Description></RegistrationInfo>`,
703
+ `<Triggers>${trigger}</Triggers>`,
704
+ '<Principals><Principal id="Author">' + `<UserId>${user}</UserId><LogonType>S4U</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>`,
705
+ "<Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>" + "<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>" + "<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>" + "<ExecutionTimeLimit>PT5M</ExecutionTimeLimit><StartWhenAvailable>true</StartWhenAvailable>" + "<Enabled>true</Enabled></Settings>",
706
+ '<Actions Context="Author"><Exec>' + `<Command>${escXml(spec.runtimeCmd)}</Command>` + `<Arguments>${escXml(`"${spec.scriptPath}" --once`)}</Arguments>` + "</Exec></Actions>",
707
+ "</Task>",
708
+ ""
709
+ ].join(`
710
+ `);
711
+ }
712
+ function buildSchtasksXmlArgs(xmlPath) {
713
+ return ["/Create", "/TN", WIN_TASK_NAME, "/XML", xmlPath, "/F"];
714
+ }
715
+ function conhostPath(platform = process.platform) {
716
+ if (platform !== "win32")
717
+ return null;
718
+ const p = join5(process.env.SystemRoot ?? "C:\\Windows", "System32", "conhost.exe");
719
+ try {
720
+ return statSync5(p).isFile() ? p : null;
721
+ } catch {
722
+ return null;
723
+ }
724
+ }
725
+ function buildSchtasksConhostArgs(spec) {
726
+ const conhost = conhostPath() ?? "C:\\Windows\\System32\\conhost.exe";
727
+ const tr = `"${conhost}" --headless "${spec.runtimeCmd}" "${spec.scriptPath}" --once`;
728
+ return ["/Create", "/TN", WIN_TASK_NAME, "/SC", "MINUTE", "/MO", String(spec.intervalMin), "/TR", tr, "/F"];
729
+ }
730
+ function buildSchtasksCreateArgs(spec) {
731
+ const tr = `"${spec.runtimeCmd}" "${spec.scriptPath}" --once`;
732
+ return ["/Create", "/TN", WIN_TASK_NAME, "/SC", "MINUTE", "/MO", String(spec.intervalMin), "/TR", tr, "/F"];
733
+ }
734
+ function buildSchtasksDeleteArgs() {
735
+ return ["/Delete", "/TN", WIN_TASK_NAME, "/F"];
736
+ }
737
+ function buildSystemdService(spec) {
738
+ return [
739
+ "[Unit]",
740
+ "Description=OpenCode QQBot watchdog (plugin-managed)",
741
+ "After=default.target",
742
+ "",
743
+ "[Service]",
744
+ "Type=oneshot",
745
+ `ExecStart="${spec.runtimeCmd}" "${spec.scriptPath}" --once`,
746
+ ""
747
+ ].join(`
748
+ `);
749
+ }
750
+ function buildSystemdTimer(intervalMin) {
751
+ return [
752
+ "[Unit]",
753
+ "Description=OpenCode QQBot watchdog timer",
754
+ "",
755
+ "[Timer]",
756
+ "OnBootSec=2min",
757
+ `OnUnitActiveSec=${intervalMin}min`,
758
+ `Unit=${SYSTEMD_UNIT}.service`,
759
+ "",
760
+ "[Install]",
761
+ "WantedBy=timers.target",
762
+ ""
763
+ ].join(`
764
+ `);
765
+ }
766
+ function buildLaunchdPlist(spec) {
767
+ const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
768
+ return [
769
+ '<?xml version="1.0" encoding="UTF-8"?>',
770
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
771
+ '<plist version="1.0">',
772
+ "<dict>",
773
+ " <key>Label</key>",
774
+ ` <string>${LAUNCHD_LABEL}</string>`,
775
+ " <key>ProgramArguments</key>",
776
+ " <array>",
777
+ ` <string>${esc(spec.runtimeCmd)}</string>`,
778
+ ` <string>${esc(spec.scriptPath)}</string>`,
779
+ " <string>--once</string>",
780
+ " </array>",
781
+ " <key>StartInterval</key>",
782
+ ` <integer>${spec.intervalMin * 60}</integer>`,
783
+ " <key>RunAtLoad</key>",
784
+ " <true/>",
785
+ "</dict>",
786
+ "</plist>",
787
+ ""
788
+ ].join(`
789
+ `);
790
+ }
791
+ function systemdDir() {
792
+ return join5(homedir4(), ".config", "systemd", "user");
793
+ }
794
+ function launchdPath() {
795
+ return join5(homedir4(), "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
796
+ }
797
+ function registeredForm(platform = process.platform) {
798
+ if (platform !== "win32")
799
+ return "unknown";
800
+ const q = run("schtasks", ["/Query", "/TN", WIN_TASK_NAME, "/XML"]);
801
+ if (!q.ok)
802
+ return "unknown";
803
+ if (/<LogonType>S4U<\/LogonType>/.test(q.detail))
804
+ return "s4u";
805
+ if (q.detail.includes("--headless") && /<Command>[^<]*conhost\.exe/i.test(q.detail))
806
+ return "conhost";
807
+ return "interactive";
808
+ }
809
+ var FORM_LABEL = {
810
+ s4u: "S4U(非交互会话,tick 零窗口)",
811
+ conhost: "conhost --headless(隐藏控制台,需已登录会话)",
812
+ interactive: "Interactive(可能闪窗)",
813
+ unknown: "未知形态"
814
+ };
815
+ function serviceInstall(spec, platform = process.platform) {
816
+ if (platform === "win32") {
817
+ const xmlPath = join5(tmpdir(), `openqq-watchdog-task-${process.pid}.xml`);
818
+ try {
819
+ writeFileSync3(xmlPath, Buffer.concat([
820
+ new Uint8Array([255, 254]),
821
+ Buffer.from(buildSchtasksTaskXml(spec), "utf-16le")
822
+ ]));
823
+ const res = run("schtasks", buildSchtasksXmlArgs(xmlPath));
824
+ if (res.ok) {
825
+ return { ok: true, detail: `${res.detail}
826
+ 注册形态: ${FORM_LABEL.s4u}` };
827
+ }
828
+ const xmlErr = res.detail;
829
+ rmSync2(xmlPath, { force: true });
830
+ const conhostRes = run("schtasks", buildSchtasksConhostArgs(spec));
831
+ if (conhostRes.ok) {
832
+ return { ok: true, detail: `${conhostRes.detail}
833
+ 注册形态: ${FORM_LABEL.conhost}
834
+ (S4U 注册失败,已回退 conhost --headless 梯队,schtasks 原始输出:${xmlErr})` };
835
+ }
836
+ const legacy = run("schtasks", buildSchtasksCreateArgs(spec));
837
+ return {
838
+ ...legacy,
839
+ detail: `${legacy.detail}
840
+ (S4U 与 conhost --headless 梯队均失败,已回退 Interactive 形态;S4U 输出:${xmlErr} | conhost 输出:${conhostRes.detail})`
841
+ };
842
+ } finally {
843
+ try {
844
+ rmSync2(xmlPath, { force: true });
845
+ } catch {}
846
+ }
847
+ }
848
+ if (platform === "linux") {
849
+ const dir = systemdDir();
850
+ mkdirSync2(dir, { recursive: true });
851
+ writeFileSync3(join5(dir, `${SYSTEMD_UNIT}.service`), buildSystemdService(spec));
852
+ writeFileSync3(join5(dir, `${SYSTEMD_UNIT}.timer`), buildSystemdTimer(spec.intervalMin));
853
+ const reload = run("systemctl", ["--user", "daemon-reload"]);
854
+ if (!reload.ok)
855
+ return reload;
856
+ const enable = run("systemctl", ["--user", "enable", "--now", `${SYSTEMD_UNIT}.timer`]);
857
+ return {
858
+ ok: enable.ok,
859
+ detail: `${enable.detail}
860
+ 提示:无图形会话时需 loginctl enable-linger $USER 才能常驻`
861
+ };
862
+ }
863
+ if (platform === "darwin") {
864
+ const path = launchdPath();
865
+ mkdirSync2(join5(homedir4(), "Library", "LaunchAgents"), { recursive: true });
866
+ writeFileSync3(path, buildLaunchdPlist(spec));
867
+ return run("launchctl", ["load", "-w", path]);
868
+ }
869
+ return { ok: false, detail: `不支持的平台:${platform}` };
870
+ }
871
+ function serviceUninstall(platform = process.platform) {
872
+ if (platform === "win32")
873
+ return run("schtasks", buildSchtasksDeleteArgs());
874
+ if (platform === "linux") {
875
+ run("systemctl", ["--user", "disable", "--now", `${SYSTEMD_UNIT}.timer`]);
876
+ rmSync2(join5(systemdDir(), `${SYSTEMD_UNIT}.timer`), { force: true });
877
+ rmSync2(join5(systemdDir(), `${SYSTEMD_UNIT}.service`), { force: true });
878
+ return run("systemctl", ["--user", "daemon-reload"]);
879
+ }
880
+ if (platform === "darwin") {
881
+ const path = launchdPath();
882
+ const res = run("launchctl", ["unload", "-w", path]);
883
+ rmSync2(path, { force: true });
884
+ return res;
885
+ }
886
+ return { ok: false, detail: `不支持的平台:${platform}` };
887
+ }
888
+ function serviceStatus(platform = process.platform) {
889
+ if (platform === "win32") {
890
+ const q = run("schtasks", ["/Query", "/TN", WIN_TASK_NAME]);
891
+ const form = q.ok ? `注册形态: ${FORM_LABEL[registeredForm(platform)]}` : "任务未注册";
892
+ return { ...q, detail: `${q.detail}
893
+ ${form}` };
894
+ }
895
+ if (platform === "linux") {
896
+ const exists = existsSync5(join5(systemdDir(), `${SYSTEMD_UNIT}.timer`));
897
+ const active = run("systemctl", ["--user", "is-active", `${SYSTEMD_UNIT}.timer`]);
898
+ return { ok: exists && active.ok, detail: `unit 文件存在=${exists}
899
+ ${active.detail}` };
900
+ }
901
+ if (platform === "darwin") {
902
+ const path = launchdPath();
903
+ return { ok: existsSync5(path), detail: `${path} 存在=${existsSync5(path)}
904
+ ${run("launchctl", ["list", LAUNCHD_LABEL]).detail}` };
905
+ }
906
+ return { ok: false, detail: `不支持的平台:${platform}` };
907
+ }
908
+
909
+ // src/cli/openqq-main.ts
910
+ var DEFAULT_INTERVAL_MIN = 10;
911
+ function sibling(name) {
912
+ const here = dirname4(fileURLToPath2(import.meta.url));
913
+ const candidates = [join6(here, name), join6(here, "..", "dist", name)];
914
+ return candidates.find((p) => existsSync6(p)) ?? candidates[0];
915
+ }
916
+ function runtimeCommand() {
917
+ const runtime = resolveRuntime();
918
+ if (runtime === "bun")
919
+ return resolveBunCommand() ?? throwNoRuntime("bun");
920
+ if (runtime === "node")
921
+ return locateOnPath("node") ?? throwNoRuntime("node");
922
+ throw new Error("未找到 bun/node 运行时");
923
+ }
924
+ function throwNoRuntime(kind) {
925
+ throw new Error(`未找到 ${kind} 全路径可执行体——注册动作需要全路径命令(静默红线)`);
926
+ }
927
+ function printResult(label, r) {
928
+ console.log(`[${label}] ${r.ok ? "OK" : "FAIL"}
929
+ ${r.detail}`);
930
+ process.exitCode = r.ok ? 0 : 1;
931
+ }
932
+ function parseFlag(argv, name) {
933
+ const i = argv.indexOf(name);
934
+ return i >= 0 ? argv[i + 1] ?? "" : null;
935
+ }
936
+ async function main() {
937
+ const [cmd, sub] = process.argv.slice(2);
938
+ if (cmd === "restart") {
939
+ const force = process.argv.includes("--force");
940
+ const timeoutMin = Number(parseFlag(process.argv.slice(2), "--timeout-min"));
941
+ const res = await restartBot({
942
+ force,
943
+ timeoutMs: Number.isFinite(timeoutMin) && timeoutMin > 0 ? timeoutMin * 60000 : undefined,
944
+ spawnFromUrl: import.meta.url,
945
+ log: (line) => console.log(line)
946
+ });
947
+ console.log(`[restart] ${res.action}(${res.reason})killed=${res.killedPid ?? "-"} spawned=${res.spawnedPid ?? "-"}`);
948
+ process.exitCode = res.action === "restarted" ? 0 : 2;
949
+ return;
950
+ }
951
+ if (cmd === "service") {
952
+ const spec = {
953
+ runtimeCmd: runtimeCommand(),
954
+ scriptPath: sibling("openqq-watchdog.js"),
955
+ intervalMin: DEFAULT_INTERVAL_MIN
956
+ };
957
+ if (sub === "install")
958
+ return printResult("service install", serviceInstall(spec));
959
+ if (sub === "uninstall")
960
+ return printResult("service uninstall", serviceUninstall());
961
+ if (sub === "status") {
962
+ const r = serviceStatus();
963
+ return printResult("service status", {
964
+ ok: r.ok,
965
+ detail: `runtime=${spec.runtimeCmd}
966
+ script=${spec.scriptPath}
967
+ ${r.detail}`
968
+ });
969
+ }
970
+ console.error("用法:openqq service install|uninstall|status");
971
+ process.exitCode = 2;
972
+ return;
973
+ }
974
+ console.error("用法:openqq-cli restart [--force] [--timeout-min N] | service install|uninstall|status");
975
+ process.exitCode = 2;
976
+ }
977
+ main().catch((error) => {
978
+ console.error("[openqq-cli] 执行失败:", error instanceof Error ? error.message : error);
979
+ process.exit(1);
980
+ });