@linjz/opencode-qqbot 0.3.16 → 0.3.18

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 (45) hide show
  1. package/README.md +316 -266
  2. package/README.zh-CN.md +326 -0
  3. package/dist/notify-cli.js +64 -12
  4. package/dist/opencode-qqbot-plugin.js +591 -92
  5. package/dist/openqq-bot.js +1172 -303
  6. package/dist/openqq-cli.js +253 -64
  7. package/dist/openqq-watchdog.js +373 -110
  8. package/package.json +4 -3
  9. package/src/bridge.ts +448 -32
  10. package/src/cli/notify.ts +4 -1
  11. package/src/cli/watchdog-main.ts +22 -7
  12. package/src/commands.ts +74 -58
  13. package/src/config.ts +39 -5
  14. package/src/core/bot-config.ts +66 -0
  15. package/src/core/bot-control.ts +21 -3
  16. package/src/core/bot-launcher.ts +4 -2
  17. package/src/core/cron-reminders.ts +84 -0
  18. package/src/core/delivery.ts +24 -1
  19. package/src/core/discovery.ts +207 -169
  20. package/src/core/error-rescue.ts +1 -1
  21. package/src/core/file-log.ts +16 -7
  22. package/src/core/inflight-journal.ts +1 -0
  23. package/src/core/instance-lock.ts +32 -1
  24. package/src/core/log-rotate.ts +91 -0
  25. package/src/core/mirror.ts +13 -4
  26. package/src/core/notices.ts +62 -0
  27. package/src/core/outbound-sanitize.ts +29 -0
  28. package/src/core/permission.ts +16 -0
  29. package/src/core/qq-instructions.ts +122 -0
  30. package/src/core/queue-view.ts +1 -0
  31. package/src/core/send-media.ts +29 -2
  32. package/src/core/send-requests.ts +227 -0
  33. package/src/core/start-error.ts +26 -0
  34. package/src/core/stt.ts +55 -0
  35. package/src/core/supervisor-election.ts +53 -0
  36. package/src/core/turn-correction.ts +68 -0
  37. package/src/core/watchdog.ts +171 -14
  38. package/src/index.ts +262 -250
  39. package/src/opencode/client.ts +32 -1
  40. package/src/opencode/mirror.ts +17 -4
  41. package/src/opencode/sessions.ts +20 -1
  42. package/src/plugin-entry.ts +67 -2
  43. package/src/qq/gateway.ts +35 -0
  44. package/src/qq/media.ts +21 -0
  45. package/src/qq/sender.ts +50 -1
@@ -1,11 +1,102 @@
1
1
  // src/core/watchdog.ts
2
- import { readFileSync, statSync, unlinkSync, writeFileSync } from "fs";
3
- import { join } from "path";
2
+ import { existsSync as existsSync2, readFileSync as readFileSync2, statSync as statSync3, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "fs";
3
+ import { dirname, join as join2 } from "path";
4
4
  import { homedir } from "os";
5
+
6
+ // src/core/log-rotate.ts
7
+ import { existsSync, renameSync, rmSync, statSync } from "fs";
8
+ var MB = 1024 * 1024;
9
+ var num = (v, d) => {
10
+ const n = Number(v);
11
+ return Number.isFinite(n) && n > 0 ? n : d;
12
+ };
13
+ function logLimitsFromEnv(env = process.env) {
14
+ return {
15
+ maxBytes: num(env.QQ_LOG_MAX_MB, 20) * MB,
16
+ keepBackups: Math.floor(num(env.QQ_LOG_KEEP, 4)),
17
+ totalBudgetBytes: num(env.QQ_LOG_TOTAL_MB, 100) * MB
18
+ };
19
+ }
20
+ function rotateLogIfNeeded(logPath, limits = logLimitsFromEnv()) {
21
+ try {
22
+ if (!existsSync(logPath) || statSync(logPath).size <= limits.maxBytes)
23
+ return false;
24
+ try {
25
+ rmSync(`${logPath}.${limits.keepBackups}`, { force: true });
26
+ } catch {}
27
+ for (let i = limits.keepBackups - 1;i >= 1; i--) {
28
+ const from = `${logPath}.${i}`;
29
+ if (!existsSync(from))
30
+ continue;
31
+ try {
32
+ renameSync(from, `${logPath}.${i + 1}`);
33
+ } catch {}
34
+ }
35
+ try {
36
+ renameSync(logPath, `${logPath}.1`);
37
+ } catch {
38
+ return false;
39
+ }
40
+ return true;
41
+ } catch {
42
+ return false;
43
+ }
44
+ }
45
+ function enforceLogBudget(logPath, limits = logLimitsFromEnv()) {
46
+ try {
47
+ const sizes = new Map;
48
+ let total = 0;
49
+ for (let i = 0;i <= 64; i++) {
50
+ const p = i === 0 ? logPath : `${logPath}.${i}`;
51
+ if (!existsSync(p))
52
+ break;
53
+ const s = statSync(p).size;
54
+ sizes.set(i, s);
55
+ total += s;
56
+ }
57
+ for (let i = limits.keepBackups;i >= 1 && total > limits.totalBudgetBytes; i--) {
58
+ const s = sizes.get(i);
59
+ if (s === undefined)
60
+ continue;
61
+ try {
62
+ rmSync(`${logPath}.${i}`, { force: true });
63
+ total -= s;
64
+ } catch {}
65
+ }
66
+ } catch {}
67
+ }
68
+
69
+ // src/core/instance-lock.ts
70
+ import { openSync, readFileSync, readdirSync, writeFileSync, closeSync, unlinkSync, statSync as statSync2, utimesSync, mkdirSync } from "fs";
71
+ import { join } from "path";
72
+ function releaseLocksOfPid(pid, dir) {
73
+ let names;
74
+ try {
75
+ names = readdirSync(dir);
76
+ } catch {
77
+ return [];
78
+ }
79
+ const cleared = [];
80
+ for (const name of names) {
81
+ if (!/^openqq-.+\.lock$/.test(name))
82
+ continue;
83
+ const p = join(dir, name);
84
+ try {
85
+ const holder = JSON.parse(readFileSync(p, "utf-8"));
86
+ if (holder.pid === pid) {
87
+ unlinkSync(p);
88
+ cleared.push(p);
89
+ }
90
+ } catch {}
91
+ }
92
+ return cleared;
93
+ }
94
+
95
+ // src/core/watchdog.ts
5
96
  var HEARTBEAT_STALE_MS = 5 * 60000;
6
97
  function botWatchdogPaths(appId) {
7
- const dir = join(homedir(), ".openqq");
8
- return { lockPath: join(dir, `openqq-${appId}.lock`), heartbeatPath: join(dir, "heartbeat") };
98
+ const dir = join2(homedir(), ".openqq");
99
+ return { lockPath: join2(dir, `openqq-${appId}.lock`), heartbeatPath: join2(dir, "heartbeat") };
9
100
  }
10
101
  function isPidAlive(pid) {
11
102
  if (!Number.isInteger(pid) || pid <= 0)
@@ -19,7 +110,7 @@ function isPidAlive(pid) {
19
110
  }
20
111
  function ageOf(path, now) {
21
112
  try {
22
- return Math.max(0, now - statSync(path).mtimeMs);
113
+ return Math.max(0, now - statSync3(path).mtimeMs);
23
114
  } catch {
24
115
  return null;
25
116
  }
@@ -29,7 +120,7 @@ function readBotHealth(paths, now = Date.now()) {
29
120
  let lockPid = null;
30
121
  if (lockAgeMs !== null) {
31
122
  try {
32
- const raw = JSON.parse(readFileSync(paths.lockPath, "utf-8"));
123
+ const raw = JSON.parse(readFileSync2(paths.lockPath, "utf-8"));
33
124
  if (typeof raw.pid === "number" && Number.isInteger(raw.pid))
34
125
  lockPid = raw.pid;
35
126
  } catch {}
@@ -41,29 +132,30 @@ function readBotHealth(paths, now = Date.now()) {
41
132
  heartbeatAgeMs: ageOf(paths.heartbeatPath, now)
42
133
  };
43
134
  }
44
- function readEnvField(envPath, key) {
135
+ function isBotDown(health) {
136
+ return health.lockPid === null || health.pidAlive === false;
137
+ }
138
+ function appendWatchdogLog(line) {
45
139
  try {
46
- for (const line of readFileSync(envPath, "utf-8").split(`
47
- `)) {
48
- const trimmed = line.trim();
49
- if (!trimmed || trimmed.startsWith("#"))
50
- continue;
51
- const eq = trimmed.indexOf("=");
52
- if (eq < 0)
53
- continue;
54
- if (trimmed.slice(0, eq).trim() === key)
55
- return trimmed.slice(eq + 1).trim();
140
+ const logPath = join2(homedir(), ".openqq", "openqq.log");
141
+ const limits = logLimitsFromEnv();
142
+ if (existsSync2(logPath) && statSync3(logPath).size > limits.maxBytes) {
143
+ if (rotateLogIfNeeded(logPath, limits))
144
+ enforceLogBudget(logPath, limits);
56
145
  }
57
- return null;
58
- } catch {
59
- return null;
60
- }
146
+ writeFileSync2(logPath, `${new Date().toISOString()} ${line}
147
+ `, { flag: "a" });
148
+ } catch {}
61
149
  }
62
- function appendWatchdogLog(line) {
150
+ function appendKillLog(entry, logPath = join2(homedir(), ".openqq", "kills.log")) {
63
151
  try {
64
- const dir = join(homedir(), ".openqq");
65
- writeFileSync(join(dir, "watchdog.log"), `${new Date().toISOString()} ${line}
152
+ writeFileSync2(logPath, `${JSON.stringify(entry)}
66
153
  `, { flag: "a" });
154
+ const limits = logLimitsFromEnv();
155
+ if (existsSync2(logPath) && statSync3(logPath).size > limits.maxBytes) {
156
+ if (rotateLogIfNeeded(logPath, limits))
157
+ enforceLogBudget(logPath, limits);
158
+ }
67
159
  } catch {}
68
160
  }
69
161
  var DEFAULT_SUPERVISOR_POLICY = {
@@ -102,7 +194,7 @@ var defaultSupervisorKill = (pid, signal) => {
102
194
  };
103
195
  function readJson(path, fallback) {
104
196
  try {
105
- return { ...fallback, ...JSON.parse(readFileSync(path, "utf-8")) };
197
+ return { ...fallback, ...JSON.parse(readFileSync2(path, "utf-8")) };
106
198
  } catch {
107
199
  return fallback;
108
200
  }
@@ -114,12 +206,12 @@ async function superviseOnce(deps) {
114
206
  const sleep = deps.sleep ?? defaultSleep;
115
207
  const kill = deps.kill ?? defaultSupervisorKill;
116
208
  const isAlive = deps.isAlive ?? isPidAlive;
117
- const statePath = deps.statePath ?? join(homedir(), ".openqq", "supervisor.json");
118
- const claimPath = deps.claimPath ?? join(homedir(), ".openqq", "supervisor.lock");
209
+ const statePath = deps.statePath ?? join2(homedir(), ".openqq", "supervisor.json");
210
+ const claimPath = deps.claimPath ?? join2(homedir(), ".openqq", "supervisor.lock");
119
211
  const audit = (line) => {
120
212
  if (deps.auditLogPath) {
121
213
  try {
122
- writeFileSync(deps.auditLogPath, `${new Date().toISOString()} ${line}
214
+ writeFileSync2(deps.auditLogPath, `${new Date().toISOString()} ${line}
123
215
  `, { flag: "a" });
124
216
  return;
125
217
  } catch {}
@@ -131,13 +223,13 @@ async function superviseOnce(deps) {
131
223
  return { action: "yield", detail: `监督者 pid=${claim.pid} 持锁中`, killedPid: null, spawnedPid: null };
132
224
  }
133
225
  try {
134
- writeFileSync(claimPath, JSON.stringify({ pid: process.pid, ts: now }));
226
+ writeFileSync2(claimPath, JSON.stringify({ pid: process.pid, ts: now }));
135
227
  } catch {
136
228
  return { action: "yield", detail: "认领锁不可写", killedPid: null, spawnedPid: null };
137
229
  }
138
230
  const release = () => {
139
231
  try {
140
- writeFileSync(claimPath, JSON.stringify({ pid: 0, ts: 0 }));
232
+ writeFileSync2(claimPath, JSON.stringify({ pid: 0, ts: 0 }));
141
233
  } catch {}
142
234
  };
143
235
  try {
@@ -171,15 +263,15 @@ async function superviseOnce(deps) {
171
263
  return { action: "yield", detail: action.reason, killedPid: null, spawnedPid: null };
172
264
  }
173
265
  if (action.kind === "give-up") {
174
- const message = `⚠️ QQBot 看门狗已放弃:${action.restarts} 次重启/${Math.round(policy.windowMs / 60000)} 分钟仍不健康。继续自动重启没有意义(同因反复死亡),请人工检查 %TEMP%\\opencode 下 bot.out.log 与 ~/.openqq/watchdog.log。`;
266
+ const message = `⚠️ QQBot 看门狗已达重启强度上限:${action.restarts} 次/${Math.round(policy.windowMs / 60000)} 分钟仍不健康(同因反复死亡)。降频重试继续——巡检不会停,强度窗口滑动后自动恢复,引擎/环境自愈即自行好转;若持续收到此告警,请检查 ~/.openqq/openqq.log(bot 与看门狗统一日志)。`;
175
267
  audit(`give-up:${message}`);
176
- log(`[supervisor] give-up:${action.restarts} 次重启仍异常,停止循环并上报`);
268
+ log(`[supervisor] give-up:${action.restarts} 次重启仍异常,降频重试继续并上报(不再永动猛拉)`);
177
269
  const lastAlert = state.alertedAt ?? 0;
178
270
  if (now - lastAlert > 30 * 60000) {
179
271
  try {
180
272
  deps.alert?.(message);
181
273
  state.alertedAt = now;
182
- writeFileSync(statePath, JSON.stringify(state));
274
+ writeFileSync2(statePath, JSON.stringify(state));
183
275
  } catch {}
184
276
  }
185
277
  return { action: "give-up", detail: message, killedPid: null, spawnedPid: null };
@@ -220,37 +312,102 @@ async function superviseOnce(deps) {
220
312
  killedPid = pid;
221
313
  }
222
314
  try {
223
- if (killedPid !== null || health.lockPid === null || health.pidAlive === false) {
224
- unlinkSync(deps.paths.lockPath);
225
- audit(`清锁:${deps.paths.lockPath}(${action.reason})`);
315
+ const locksDir = dirname(deps.paths.lockPath);
316
+ let cleared = [];
317
+ if (killedPid !== null) {
318
+ cleared = releaseLocksOfPid(killedPid, locksDir);
319
+ } else if (health.pidAlive === false && health.lockPid !== null) {
320
+ cleared = releaseLocksOfPid(health.lockPid, locksDir);
321
+ }
322
+ if (existsSync2(deps.paths.lockPath)) {
323
+ try {
324
+ unlinkSync2(deps.paths.lockPath);
325
+ if (!cleared.includes(deps.paths.lockPath))
326
+ cleared.push(deps.paths.lockPath);
327
+ } catch {}
226
328
  }
329
+ if (cleared.length > 0)
330
+ audit(`清锁:${cleared.join("、")}(${action.reason})`);
227
331
  } catch {}
228
332
  const spawnedPid = deps.spawn();
229
333
  state.restartLog.push(Date.now());
230
334
  state.restartLog = state.restartLog.filter((t) => t > Date.now() - policy.windowMs * 2);
231
335
  try {
232
- writeFileSync(statePath, JSON.stringify(state));
336
+ writeFileSync2(statePath, JSON.stringify(state));
233
337
  } catch {
234
338
  log("[supervisor] 强度账落盘失败(不影响本次拉起)");
235
339
  }
236
- const detail = `${action.reason};${killedPid ? `已优雅停 pid=${killedPid};` : ""}已拉起 pid=${spawnedPid}`;
340
+ let livenessVerdict = "alive";
341
+ let respawnPid = null;
342
+ if (deps.livenessCheck !== false) {
343
+ const graceWaitMs = 1e4;
344
+ await sleep(graceWaitMs);
345
+ const liveness = readBotHealth(deps.paths, Date.now());
346
+ if (!isPidAlive(spawnedPid) || liveness.lockPid === null) {
347
+ livenessVerdict = `dead-after-spawn(10s 复核:进程${isPidAlive(spawnedPid) ? "在但锁未建立" : "已退出"})`;
348
+ audit(`二次追击:拉起 pid=${spawnedPid} 失败(${livenessVerdict}),立即重拉`);
349
+ try {
350
+ const locksDir2 = dirname(deps.paths.lockPath);
351
+ let cleared2 = [];
352
+ if (!isPidAlive(spawnedPid) && existsSync2(deps.paths.lockPath)) {
353
+ cleared2 = releaseLocksOfPid(spawnedPid, locksDir2);
354
+ }
355
+ if (existsSync2(deps.paths.lockPath)) {
356
+ try {
357
+ unlinkSync2(deps.paths.lockPath);
358
+ if (!cleared2.includes(deps.paths.lockPath))
359
+ cleared2.push(deps.paths.lockPath);
360
+ } catch {}
361
+ }
362
+ if (cleared2.length > 0)
363
+ audit(`清锁:${cleared2.join("、")}(二次追击前清场)`);
364
+ } catch {}
365
+ respawnPid = deps.spawn();
366
+ await sleep(graceWaitMs);
367
+ const liveness2 = readBotHealth(deps.paths, Date.now());
368
+ if (!isPidAlive(respawnPid) || liveness2.lockPid === null) {
369
+ livenessVerdict += `;二次拉起 pid=${respawnPid} 仍失败——交下轮巡检接力(强度账 ${state.restartLog.length}/${policy.maxRestarts})`;
370
+ } else {
371
+ livenessVerdict += `;二次拉起 pid=${respawnPid} 成功`;
372
+ }
373
+ }
374
+ }
375
+ if (killedPid !== null || livenessVerdict !== "alive") {
376
+ appendKillLog({
377
+ kind: "decision",
378
+ reason: action.reason,
379
+ health: {
380
+ lockPid: health.lockPid,
381
+ pidAlive: health.pidAlive,
382
+ heartbeatAgeMs: health.heartbeatAgeMs,
383
+ lockAgeMs: health.lockAgeMs
384
+ },
385
+ killedPid,
386
+ killEscalation: killedPid !== null ? "TERM" : "n/a",
387
+ spawnedPid: respawnPid ?? spawnedPid,
388
+ restartIntensity: `${state.restartLog.length}/${policy.maxRestarts}`,
389
+ livenessVerdict: livenessVerdict !== "alive" ? livenessVerdict : "alive",
390
+ at: Date.now()
391
+ });
392
+ }
393
+ const detail = `${action.reason};${killedPid ? `已优雅停 pid=${killedPid};` : ""}已拉起 pid=${respawnPid ?? spawnedPid}${livenessVerdict !== "alive" ? `;${livenessVerdict}` : ""}`;
237
394
  audit(killedPid ? `主动杀:${detail}` : `验尸拉新:${detail}`);
238
- return { action: "restart", detail, killedPid, spawnedPid };
395
+ return { action: "restart", detail, killedPid, spawnedPid: respawnPid ?? spawnedPid };
239
396
  } finally {
240
397
  release();
241
398
  }
242
399
  }
243
400
 
244
401
  // src/core/bot-control.ts
245
- import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
246
- import { dirname as dirname2, join as join3 } from "path";
402
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
403
+ import { dirname as dirname3, join as join4 } from "path";
247
404
  import { homedir as homedir3 } from "os";
248
405
  import { fileURLToPath } from "url";
249
406
 
250
407
  // src/core/bot-launcher.ts
251
408
  import { spawn, spawnSync } from "child_process";
252
- import { existsSync, readFileSync as readFileSync2, statSync as statSync2 } from "fs";
253
- import { join as join2, dirname, isAbsolute } from "path";
409
+ import { existsSync as existsSync3, readFileSync as readFileSync3, statSync as statSync4 } from "fs";
410
+ import { join as join3, dirname as dirname2, isAbsolute } from "path";
254
411
  import { homedir as homedir2 } from "os";
255
412
  function resolveRuntime(probe = defaultProbe) {
256
413
  if (resolveBunCommand(probe))
@@ -261,7 +418,7 @@ function resolveRuntime(probe = defaultProbe) {
261
418
  }
262
419
  function isExecutable(p) {
263
420
  try {
264
- const st = statSync2(p);
421
+ const st = statSync4(p);
265
422
  return st.isFile() && (process.platform === "win32" || (st.mode & 73) !== 0);
266
423
  } catch {
267
424
  return false;
@@ -275,7 +432,7 @@ function locateOnPath(cmd, pathEnv = process.env.PATH ?? process.env.Path ?? "")
275
432
  if (!dir)
276
433
  continue;
277
434
  const base = isWin && !/\.[a-z]+$/i.test(cmd) ? `${cmd}.exe` : cmd;
278
- const full = join2(dir, base);
435
+ const full = join3(dir, base);
279
436
  if (isExecutable(full))
280
437
  return full;
281
438
  }
@@ -290,16 +447,16 @@ function resolveThroughShim(bare, pathEnv = process.env.PATH ?? process.env.Path
290
447
  if (!dir)
291
448
  continue;
292
449
  for (const ext of [".cmd", ".bat"]) {
293
- const shimPath = join2(dir, bare + ext);
450
+ const shimPath = join3(dir, bare + ext);
294
451
  let text;
295
452
  try {
296
- text = readFileSync2(shimPath, "utf-8");
453
+ text = readFileSync3(shimPath, "utf-8");
297
454
  } catch {
298
455
  continue;
299
456
  }
300
457
  const rel = SHIM_PATTERN_LINE.exec(text);
301
458
  if (rel) {
302
- const full = join2(dir, rel[1]);
459
+ const full = join3(dir, rel[1]);
303
460
  if (isExecutable(full))
304
461
  return full;
305
462
  }
@@ -315,15 +472,15 @@ function resolveThroughShim(bare, pathEnv = process.env.PATH ?? process.env.Path
315
472
  }
316
473
  function bunCandidates() {
317
474
  if (process.platform === "win32") {
318
- const appdata = process.env.APPDATA || join2(homedir2(), "AppData", "Roaming");
475
+ const appdata = process.env.APPDATA || join3(homedir2(), "AppData", "Roaming");
319
476
  return [
320
- join2(appdata, "npm", "node_modules", "bun", "bin", "bun.exe"),
321
- join2(homedir2(), ".bun", "bin", "bun.exe"),
477
+ join3(appdata, "npm", "node_modules", "bun", "bin", "bun.exe"),
478
+ join3(homedir2(), ".bun", "bin", "bun.exe"),
322
479
  "bun",
323
480
  "bun.exe"
324
481
  ];
325
482
  }
326
- return ["/usr/local/bin/bun", "/opt/homebrew/bin/bun", join2(homedir2(), ".bun", "bin", "bun"), "bun"];
483
+ return ["/usr/local/bin/bun", "/opt/homebrew/bin/bun", join3(homedir2(), ".bun", "bin", "bun"), "bun"];
327
484
  }
328
485
  function resolveBunCommand(probe = defaultProbe) {
329
486
  if (probe !== defaultProbe) {
@@ -378,7 +535,7 @@ function buildLaunchPlan(runtime, entry, logPath) {
378
535
  return { command: resolveRuntimeCommand("node"), args: [entry], env };
379
536
  }
380
537
  function botLogPath() {
381
- return join2(homedir2(), ".openqq", "bot.out.log");
538
+ return join3(homedir2(), ".openqq", "openqq.log");
382
539
  }
383
540
  function spawnBotDetached(plan) {
384
541
  const child = spawn(plan.command, plan.args, {
@@ -395,31 +552,48 @@ function spawnBotDetached(plan) {
395
552
  }
396
553
 
397
554
  // src/core/bot-control.ts
398
- function resolveInstalledBotEntry(fromUrl, exists = existsSync2) {
399
- const here = dirname2(fileURLToPath(fromUrl));
555
+ function resolveInstalledBotEntry(fromUrl, exists = existsSync4) {
556
+ const here = dirname3(fileURLToPath(fromUrl));
400
557
  const candidates = [
401
- join3(here, "openqq-bot.js"),
402
- join3(here, "..", "dist", "openqq-bot.js"),
403
- join3(here, "..", "src", "index.ts"),
404
- join3(here, "..", "..", "src", "index.ts")
558
+ join4(here, "openqq-bot.js"),
559
+ join4(here, "..", "dist", "openqq-bot.js"),
560
+ join4(here, "..", "src", "index.ts"),
561
+ join4(here, "..", "..", "src", "index.ts")
405
562
  ];
406
563
  for (const c of candidates)
407
564
  if (exists(c))
408
565
  return c;
409
566
  return null;
410
567
  }
411
- function readAppId(envPath = join3(homedir3(), ".openqq", ".env")) {
568
+ function readAppId(envPath = join4(homedir3(), ".openqq", ".env")) {
569
+ let botsRaw = null;
412
570
  try {
413
- for (const line of readFileSync3(envPath, "utf-8").split(`
571
+ for (const line of readFileSync4(envPath, "utf-8").split(`
414
572
  `)) {
415
573
  const t = line.trim();
416
574
  if (!t || t.startsWith("#"))
417
575
  continue;
418
576
  const eq = t.indexOf("=");
419
- if (eq > 0 && t.slice(0, eq).trim() === "QQ_APP_ID")
420
- return t.slice(eq + 1).trim() || null;
577
+ if (eq < 0)
578
+ continue;
579
+ const key = t.slice(0, eq).trim();
580
+ if (key === "QQ_APP_ID") {
581
+ const v = t.slice(eq + 1).trim();
582
+ if (v)
583
+ return v;
584
+ }
585
+ if (key === "QQ_BOTS")
586
+ botsRaw = t.slice(eq + 1).trim();
421
587
  }
422
588
  } catch {}
589
+ if (botsRaw) {
590
+ try {
591
+ const arr = JSON.parse(botsRaw);
592
+ const first = Array.isArray(arr) ? arr[0]?.appId : undefined;
593
+ if (typeof first === "string" && first)
594
+ return first;
595
+ } catch {}
596
+ }
423
597
  return null;
424
598
  }
425
599
  function startBot(fromUrl, log = () => {}) {
@@ -435,34 +609,61 @@ function startBot(fromUrl, log = () => {}) {
435
609
  return pid;
436
610
  }
437
611
 
612
+ // src/core/supervisor-election.ts
613
+ import { readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
614
+ import { join as join5 } from "path";
615
+ import { homedir as homedir4 } from "os";
616
+ var LEASE_PATH = join5(homedir4(), ".openqq", "supervisor-lease.json");
617
+ var LEASE_TTL_MS = 10 * 60000;
618
+ function electSupervisor(channel, opts) {
619
+ const ttlMs = opts?.ttlMs ?? LEASE_TTL_MS;
620
+ const now = opts?.now ?? Date.now();
621
+ const path = opts?.path ?? LEASE_PATH;
622
+ try {
623
+ let cur = null;
624
+ try {
625
+ cur = JSON.parse(readFileSync5(path, "utf-8"));
626
+ } catch {}
627
+ if (cur && typeof cur.until === "number" && cur.until > now) {
628
+ const mine = cur.channel === channel && cur.pid === process.pid;
629
+ if (!mine)
630
+ return false;
631
+ }
632
+ writeFileSync3(path, JSON.stringify({ channel, pid: process.pid, until: now + ttlMs }));
633
+ return true;
634
+ } catch {
635
+ return true;
636
+ }
637
+ }
638
+
438
639
  // src/cli/notify.ts
439
- import { existsSync as existsSync5, readFileSync as readFileSync6 } from "node:fs";
640
+ import { existsSync as existsSync8, readFileSync as readFileSync9 } from "node:fs";
440
641
 
441
642
  // src/core/storage.ts
442
- import { homedir as homedir4 } from "os";
443
- import { join as join4 } from "path";
444
- var LEGACY_ROOT = join4(homedir4(), ".openqq");
643
+ import { homedir as homedir5 } from "os";
644
+ import { join as join6 } from "path";
645
+ var LEGACY_ROOT = join6(homedir5(), ".openqq");
445
646
  function storageRoot(appId) {
446
647
  const base = (process.env.QQ_DATA_DIR ?? "").trim() || LEGACY_ROOT;
447
- return appId ? join4(base, "roles", appId) : base;
648
+ return appId ? join6(base, "roles", appId) : base;
448
649
  }
449
650
  function storageFile(name, appId) {
450
- return join4(storageRoot(appId), name);
651
+ return join6(storageRoot(appId), name);
451
652
  }
452
653
 
453
654
  // src/core/outbox.ts
454
655
  import {
455
- closeSync,
456
- existsSync as existsSync3,
457
- mkdirSync,
458
- openSync,
459
- readFileSync as readFileSync4,
460
- renameSync,
461
- statSync as statSync3,
462
- unlinkSync as unlinkSync2,
463
- writeFileSync as writeFileSync2
656
+ closeSync as closeSync2,
657
+ existsSync as existsSync5,
658
+ mkdirSync as mkdirSync2,
659
+ openSync as openSync2,
660
+ readFileSync as readFileSync6,
661
+ renameSync as renameSync2,
662
+ statSync as statSync5,
663
+ unlinkSync as unlinkSync3,
664
+ writeFileSync as writeFileSync4
464
665
  } from "node:fs";
465
- import { dirname as dirname3 } from "node:path";
666
+ import { dirname as dirname4 } from "node:path";
466
667
  import { randomUUID } from "node:crypto";
467
668
  var OUTBOX_SENT_RETENTION_MS = 24 * 60 * 60 * 1000;
468
669
  var OUTBOX_SENT_RETENTION_LIMIT = 20;
@@ -498,22 +699,22 @@ function delay(ms) {
498
699
  return new Promise((resolve) => setTimeout(resolve, ms));
499
700
  }
500
701
  function atomicWrite(filePath, document) {
501
- mkdirSync(dirname3(filePath), { recursive: true });
702
+ mkdirSync2(dirname4(filePath), { recursive: true });
502
703
  const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
503
704
  try {
504
- writeFileSync2(temporary, JSON.stringify(document, null, 2), { mode: 384 });
505
- renameSync(temporary, filePath);
705
+ writeFileSync4(temporary, JSON.stringify(document, null, 2), { mode: 384 });
706
+ renameSync2(temporary, filePath);
506
707
  } catch (error) {
507
708
  try {
508
- unlinkSync2(temporary);
709
+ unlinkSync3(temporary);
509
710
  } catch {}
510
711
  throw error;
511
712
  }
512
713
  }
513
714
  function readDocument(filePath, now) {
514
- if (!existsSync3(filePath))
715
+ if (!existsSync5(filePath))
515
716
  return { version: 1, entries: [] };
516
- const raw = JSON.parse(readFileSync4(filePath, "utf8"));
717
+ const raw = JSON.parse(readFileSync6(filePath, "utf8"));
517
718
  if (Array.isArray(raw)) {
518
719
  return { version: 1, entries: pruneOutboxEntries(raw, now) };
519
720
  }
@@ -544,23 +745,23 @@ function createOutbox(options = {}) {
544
745
  let stopped = false;
545
746
  let flushing;
546
747
  function withLock(fn) {
547
- mkdirSync(dirname3(filePath), { recursive: true });
748
+ mkdirSync2(dirname4(filePath), { recursive: true });
548
749
  const lockPath = `${filePath}.lock`;
549
750
  const token = `${owner}:${Date.now()}:${randomUUID()}`;
550
751
  const deadline = Date.now() + lockWaitMs;
551
752
  for (;; ) {
552
753
  try {
553
- const fd = openSync(lockPath, "wx", 384);
754
+ const fd = openSync2(lockPath, "wx", 384);
554
755
  try {
555
- writeFileSync2(fd, token);
756
+ writeFileSync4(fd, token);
556
757
  } finally {
557
- closeSync(fd);
758
+ closeSync2(fd);
558
759
  }
559
760
  break;
560
761
  } catch (error) {
561
762
  try {
562
- if (Date.now() - statSync3(lockPath).mtimeMs > lockStaleMs)
563
- unlinkSync2(lockPath);
763
+ if (Date.now() - statSync5(lockPath).mtimeMs > lockStaleMs)
764
+ unlinkSync3(lockPath);
564
765
  } catch {}
565
766
  if (Date.now() >= deadline)
566
767
  throw new Error(`Outbox 锁等待超时: ${errorText(error)}`);
@@ -571,8 +772,8 @@ function createOutbox(options = {}) {
571
772
  return fn();
572
773
  } finally {
573
774
  try {
574
- if (readFileSync4(lockPath, "utf8") === token)
575
- unlinkSync2(lockPath);
775
+ if (readFileSync6(lockPath, "utf8") === token)
776
+ unlinkSync3(lockPath);
576
777
  } catch {}
577
778
  }
578
779
  }
@@ -854,13 +1055,64 @@ function createOutbox(options = {}) {
854
1055
  }
855
1056
 
856
1057
  // src/config.ts
857
- import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
858
- import { join as join5 } from "path";
859
- import { homedir as homedir5 } from "os";
860
- var CONFIG_DIR = join5(homedir5(), ".openqq");
861
- var ENV_FILE = join5(CONFIG_DIR, ".env");
1058
+ import { existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync8, writeFileSync as writeFileSync5 } from "fs";
1059
+ import { join as join8 } from "path";
1060
+ import { homedir as homedir7 } from "os";
1061
+
1062
+ // src/core/bot-config.ts
1063
+ import { existsSync as existsSync6, readFileSync as readFileSync7 } from "node:fs";
1064
+ import { homedir as homedir6 } from "node:os";
1065
+ import { join as join7 } from "node:path";
1066
+ function configJsonPath(env = process.env) {
1067
+ return env.QQ_CONFIG_FILE?.trim() || join7(homedir6(), ".openqq", "config.json");
1068
+ }
1069
+ function parseConfigJson(raw) {
1070
+ let parsed;
1071
+ try {
1072
+ parsed = JSON.parse(raw);
1073
+ } catch {
1074
+ console.warn("[config] config.json 不是合法 JSON,已忽略");
1075
+ return {};
1076
+ }
1077
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1078
+ console.warn("[config] config.json 必须是平铺 JSON 对象,已忽略");
1079
+ return {};
1080
+ }
1081
+ const out = {};
1082
+ for (const [k, v] of Object.entries(parsed)) {
1083
+ if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
1084
+ out[k] = String(v);
1085
+ }
1086
+ }
1087
+ return out;
1088
+ }
1089
+ function computeOverlay(env, config) {
1090
+ return Object.entries(config).filter(([k]) => env[k] === undefined);
1091
+ }
1092
+ function applyConfigOverlay(env = process.env) {
1093
+ const path = configJsonPath(env);
1094
+ if (!existsSync6(path))
1095
+ return 0;
1096
+ let raw;
1097
+ try {
1098
+ raw = readFileSync7(path, "utf-8");
1099
+ } catch {
1100
+ return 0;
1101
+ }
1102
+ const overlay = computeOverlay(env, parseConfigJson(raw));
1103
+ for (const [k, v] of overlay)
1104
+ env[k] = v;
1105
+ if (overlay.length > 0) {
1106
+ console.log(`[config] config.json 已叠加 ${overlay.length} 项(env/.env 优先): ${path}`);
1107
+ }
1108
+ return overlay.length;
1109
+ }
1110
+
1111
+ // src/config.ts
1112
+ var CONFIG_DIR = join8(homedir7(), ".openqq");
1113
+ var ENV_FILE = join8(CONFIG_DIR, ".env");
862
1114
  function loadEnvFile(path) {
863
- const content = readFileSync5(path, "utf-8");
1115
+ const content = readFileSync8(path, "utf-8");
864
1116
  for (const line of content.split(`
865
1117
  `)) {
866
1118
  const trimmed = line.trim();
@@ -954,13 +1206,13 @@ function readBody(parsed) {
954
1206
  return parsed.text;
955
1207
  if (parsed.filePath !== undefined) {
956
1208
  if (parsed.filePath === "-")
957
- return readFileSync6(0, "utf8");
958
- if (!existsSync5(parsed.filePath))
1209
+ return readFileSync9(0, "utf8");
1210
+ if (!existsSync8(parsed.filePath))
959
1211
  throw new Error(`--file 不存在:${parsed.filePath}`);
960
- return readFileSync6(parsed.filePath, "utf8");
1212
+ return readFileSync9(parsed.filePath, "utf8");
961
1213
  }
962
1214
  if (parsed.stdin)
963
- return readFileSync6(0, "utf8");
1215
+ return readFileSync9(0, "utf8");
964
1216
  return "";
965
1217
  }
966
1218
  async function runNotifyCli(argv, options = {}) {
@@ -979,7 +1231,8 @@ async function runNotifyCli(argv, options = {}) {
979
1231
  console.log(help);
980
1232
  return { ok: true, queued: false, id: "", user: "", chars: 0, truncated: false, dryRun: true, json: parsed.json, reason: "help" };
981
1233
  }
982
- if (!options.env && existsSync5(ENV_FILE))
1234
+ applyConfigOverlay();
1235
+ if (!options.env && existsSync8(ENV_FILE))
983
1236
  loadEnvFile(ENV_FILE);
984
1237
  const allowedUsers = options.env ? [...options.env.allowedUsers] : String(process.env.ALLOWED_USERS ?? "").split(/[,\s]+/).filter(Boolean);
985
1238
  const user = resolveUser(allowedUsers, parsed.user);
@@ -1009,8 +1262,6 @@ async function runNotifyCli(argv, options = {}) {
1009
1262
  }
1010
1263
 
1011
1264
  // src/cli/watchdog-main.ts
1012
- import { join as join6 } from "path";
1013
- import { homedir as homedir6 } from "os";
1014
1265
  var DEFAULT_INTERVAL_MIN = 10;
1015
1266
  function parseArgs2(argv) {
1016
1267
  const loop = argv.includes("--loop");
@@ -1020,14 +1271,22 @@ function parseArgs2(argv) {
1020
1271
  return { loop, intervalMin };
1021
1272
  }
1022
1273
  function currentAppId() {
1023
- return readAppId() ?? readEnvField(join6(homedir6(), ".openqq", ".env"), "QQ_APP_ID");
1274
+ return readAppId();
1024
1275
  }
1025
1276
  function alert(message) {
1026
1277
  runNotifyCli(["--text", message, "--id", `supervisor-giveup-${Date.now()}`]).then((r) => console.log(`[supervisor] 告警已入队 user=${r.user}`), (error) => console.error("[supervisor] 告警入队失败:", error instanceof Error ? error.message : error));
1027
1278
  }
1028
1279
  async function tick(appId) {
1280
+ const paths = botWatchdogPaths(appId);
1281
+ if (!electSupervisor("service")) {
1282
+ if (!isBotDown(readBotHealth(paths, Date.now()))) {
1283
+ appendWatchdogLog("[supervisor] 让贤:plugin 通道持监督租约中,本轮跳过");
1284
+ return;
1285
+ }
1286
+ appendWatchdogLog("[supervisor] 破格接管:plugin 持租约但 bot 失能——让贤条款不适用");
1287
+ }
1029
1288
  const result = await superviseOnce({
1030
- paths: botWatchdogPaths(appId),
1289
+ paths,
1031
1290
  spawn: () => startBot(import.meta.url, (line) => console.log(line)),
1032
1291
  log: (line) => console.log(line),
1033
1292
  alert
@@ -1040,7 +1299,7 @@ async function main() {
1040
1299
  const args = parseArgs2(process.argv.slice(2));
1041
1300
  const appId = currentAppId();
1042
1301
  if (!appId) {
1043
- console.error("[watchdog] 未找到 QQ_APP_ID(~/.openqq/.env),无法定位实例锁");
1302
+ console.error("[watchdog] 未找到任何角色凭据(~/.openqq/.env 缺 QQ_APP_ID/QQ_APP_SECRET 且 QQ_BOTS 无合法角色),无法定位实例锁");
1044
1303
  process.exit(1);
1045
1304
  }
1046
1305
  console.log(`[watchdog] 模式=${args.loop ? `loop/${args.intervalMin}min` : "once"}(监督矩阵:冷却2m/强度3次15m/优雅杀8s)`);
@@ -1048,7 +1307,10 @@ async function main() {
1048
1307
  if (!args.loop)
1049
1308
  return;
1050
1309
  const timer = setInterval(() => {
1051
- tick(appId).catch((error) => console.error("[watchdog] 巡检失败:", error instanceof Error ? error.message : error));
1310
+ tick(appId).catch((error) => {
1311
+ appendWatchdogLog(`[watchdog] 巡检失败: ${error instanceof Error ? error.message : String(error)}`);
1312
+ console.error("[watchdog] 巡检失败:", error instanceof Error ? error.message : error);
1313
+ });
1052
1314
  }, args.intervalMin * 60000);
1053
1315
  const stop = () => {
1054
1316
  clearInterval(timer);
@@ -1058,6 +1320,7 @@ async function main() {
1058
1320
  process.once("SIGTERM", stop);
1059
1321
  }
1060
1322
  main().catch((error) => {
1323
+ appendWatchdogLog(`[watchdog] 致命错误: ${error instanceof Error ? error.message : String(error)}`);
1061
1324
  console.error("[watchdog] 致命错误:", error instanceof Error ? error.message : error);
1062
1325
  process.exit(1);
1063
1326
  });