@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,1326 @@
1
+ // src/core/watchdog.ts
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
+ 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
96
+ var HEARTBEAT_STALE_MS = 5 * 60000;
97
+ function botWatchdogPaths(appId) {
98
+ const dir = join2(homedir(), ".openqq");
99
+ return { lockPath: join2(dir, `openqq-${appId}.lock`), heartbeatPath: join2(dir, "heartbeat") };
100
+ }
101
+ function isPidAlive(pid) {
102
+ if (!Number.isInteger(pid) || pid <= 0)
103
+ return false;
104
+ try {
105
+ process.kill(pid, 0);
106
+ return true;
107
+ } catch (error) {
108
+ return error.code === "EPERM";
109
+ }
110
+ }
111
+ function ageOf(path, now) {
112
+ try {
113
+ return Math.max(0, now - statSync3(path).mtimeMs);
114
+ } catch {
115
+ return null;
116
+ }
117
+ }
118
+ function readBotHealth(paths, now = Date.now()) {
119
+ const lockAgeMs = ageOf(paths.lockPath, now);
120
+ let lockPid = null;
121
+ if (lockAgeMs !== null) {
122
+ try {
123
+ const raw = JSON.parse(readFileSync2(paths.lockPath, "utf-8"));
124
+ if (typeof raw.pid === "number" && Number.isInteger(raw.pid))
125
+ lockPid = raw.pid;
126
+ } catch {}
127
+ }
128
+ return {
129
+ lockPid,
130
+ lockAgeMs,
131
+ pidAlive: lockPid === null ? null : isPidAlive(lockPid),
132
+ heartbeatAgeMs: ageOf(paths.heartbeatPath, now)
133
+ };
134
+ }
135
+ function isBotDown(health) {
136
+ return health.lockPid === null || health.pidAlive === false;
137
+ }
138
+ function appendWatchdogLog(line) {
139
+ try {
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);
145
+ }
146
+ writeFileSync2(logPath, `${new Date().toISOString()} ${line}
147
+ `, { flag: "a" });
148
+ } catch {}
149
+ }
150
+ function appendKillLog(entry, logPath = join2(homedir(), ".openqq", "kills.log")) {
151
+ try {
152
+ writeFileSync2(logPath, `${JSON.stringify(entry)}
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
+ }
159
+ } catch {}
160
+ }
161
+ var DEFAULT_SUPERVISOR_POLICY = {
162
+ cooldownMs: 2 * 60000,
163
+ maxRestarts: 3,
164
+ windowMs: 15 * 60000,
165
+ graceMs: 8000,
166
+ claimTtlMs: 90000
167
+ };
168
+ function decideSupervise(health, state, now, policy = DEFAULT_SUPERVISOR_POLICY) {
169
+ const staleHeartbeat = health.heartbeatAgeMs !== null && health.heartbeatAgeMs > HEARTBEAT_STALE_MS;
170
+ const needsRestart = health.lockPid === null || health.pidAlive === false || staleHeartbeat;
171
+ if (!needsRestart)
172
+ return { kind: "ok" };
173
+ const windowStart = now - policy.windowMs;
174
+ const recentRestarts = state.restartLog.filter((t) => t > windowStart).length;
175
+ if (recentRestarts >= policy.maxRestarts)
176
+ return { kind: "give-up", restarts: recentRestarts };
177
+ const last = state.restartLog[state.restartLog.length - 1] ?? null;
178
+ if (last !== null && now - last < policy.cooldownMs)
179
+ return { kind: "cooldown", untilMs: last + policy.cooldownMs };
180
+ if (health.lockPid !== null && health.pidAlive !== false && staleHeartbeat) {
181
+ return {
182
+ kind: "grace-kill-spawn",
183
+ killPid: health.lockPid,
184
+ reason: `心跳陈旧 ${Math.round((health.heartbeatAgeMs ?? 0) / 60000)} 分钟(进程活但事件循环无进展)`
185
+ };
186
+ }
187
+ return { kind: "spawn", reason: health.lockPid === null ? "无实例锁(bot 未运行)" : "锁定进程已退出" };
188
+ }
189
+ var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
190
+ var defaultSupervisorKill = (pid, signal) => {
191
+ try {
192
+ process.kill(pid, signal);
193
+ } catch {}
194
+ };
195
+ function readJson(path, fallback) {
196
+ try {
197
+ return { ...fallback, ...JSON.parse(readFileSync2(path, "utf-8")) };
198
+ } catch {
199
+ return fallback;
200
+ }
201
+ }
202
+ async function superviseOnce(deps) {
203
+ const policy = deps.policy ?? DEFAULT_SUPERVISOR_POLICY;
204
+ const now = deps.now?.() ?? Date.now();
205
+ const log = deps.log ?? (() => {});
206
+ const sleep = deps.sleep ?? defaultSleep;
207
+ const kill = deps.kill ?? defaultSupervisorKill;
208
+ const isAlive = deps.isAlive ?? isPidAlive;
209
+ const statePath = deps.statePath ?? join2(homedir(), ".openqq", "supervisor.json");
210
+ const claimPath = deps.claimPath ?? join2(homedir(), ".openqq", "supervisor.lock");
211
+ const audit = (line) => {
212
+ if (deps.auditLogPath) {
213
+ try {
214
+ writeFileSync2(deps.auditLogPath, `${new Date().toISOString()} ${line}
215
+ `, { flag: "a" });
216
+ return;
217
+ } catch {}
218
+ }
219
+ appendWatchdogLog(line);
220
+ };
221
+ const claim = readJson(claimPath, { pid: 0, ts: 0 });
222
+ if (claim.ts && now - claim.ts < policy.claimTtlMs && claim.pid !== process.pid) {
223
+ return { action: "yield", detail: `监督者 pid=${claim.pid} 持锁中`, killedPid: null, spawnedPid: null };
224
+ }
225
+ try {
226
+ writeFileSync2(claimPath, JSON.stringify({ pid: process.pid, ts: now }));
227
+ } catch {
228
+ return { action: "yield", detail: "认领锁不可写", killedPid: null, spawnedPid: null };
229
+ }
230
+ const release = () => {
231
+ try {
232
+ writeFileSync2(claimPath, JSON.stringify({ pid: 0, ts: 0 }));
233
+ } catch {}
234
+ };
235
+ try {
236
+ const health = readBotHealth(deps.paths, now);
237
+ const state = readJson(statePath, { restartLog: [] });
238
+ let action = decideSupervise(health, state, now, policy);
239
+ if (deps.request === "manual-restart" && action.kind === "ok") {
240
+ const windowStart = now - policy.windowMs;
241
+ const recentRestarts = state.restartLog.filter((t) => t > windowStart).length;
242
+ if (recentRestarts >= policy.maxRestarts) {
243
+ return {
244
+ action: "give-up",
245
+ detail: `15 分钟内已重启 ${recentRestarts} 次(监督强度上限),人工重启亦被拦截,请排查根因`,
246
+ killedPid: null,
247
+ spawnedPid: null
248
+ };
249
+ }
250
+ const last = state.restartLog[state.restartLog.length - 1] ?? null;
251
+ if (last !== null && now - last < policy.cooldownMs) {
252
+ return { action: "cooldown", detail: `距上次重启不足 ${Math.round(policy.cooldownMs / 1000)}s(冷却期),人工重启跳过`, killedPid: null, spawnedPid: null };
253
+ }
254
+ action = health.lockPid !== null && health.pidAlive !== false ? { kind: "grace-kill-spawn", killPid: health.lockPid, reason: "人工请求重启(openqq restart)" } : { kind: "spawn", reason: "人工请求重启(bot 未运行,直接拉起)" };
255
+ }
256
+ if (action.kind === "ok")
257
+ return { action: "ok", detail: "健康", killedPid: null, spawnedPid: null };
258
+ if (action.kind === "cooldown") {
259
+ log(`[supervisor] 冷却中(上次重启 ${Math.round((now - (action.untilMs - policy.cooldownMs)) / 1000)}s 前),本轮跳过`);
260
+ return { action: "cooldown", detail: "冷却跳过", killedPid: null, spawnedPid: null };
261
+ }
262
+ if (action.kind === "yield") {
263
+ return { action: "yield", detail: action.reason, killedPid: null, spawnedPid: null };
264
+ }
265
+ if (action.kind === "give-up") {
266
+ const message = `⚠️ QQBot 看门狗已达重启强度上限:${action.restarts} 次/${Math.round(policy.windowMs / 60000)} 分钟仍不健康(同因反复死亡)。降频重试继续——巡检不会停,强度窗口滑动后自动恢复,引擎/环境自愈即自行好转;若持续收到此告警,请检查 ~/.openqq/openqq.log(bot 与看门狗统一日志)。`;
267
+ audit(`give-up:${message}`);
268
+ log(`[supervisor] give-up:${action.restarts} 次重启仍异常,降频重试继续并上报(不再永动猛拉)`);
269
+ const lastAlert = state.alertedAt ?? 0;
270
+ if (now - lastAlert > 30 * 60000) {
271
+ try {
272
+ deps.alert?.(message);
273
+ state.alertedAt = now;
274
+ writeFileSync2(statePath, JSON.stringify(state));
275
+ } catch {}
276
+ }
277
+ return { action: "give-up", detail: message, killedPid: null, spawnedPid: null };
278
+ }
279
+ let killedPid = null;
280
+ if (action.kind === "grace-kill-spawn" && action.killPid !== process.pid) {
281
+ const pid = action.killPid;
282
+ if (deps.request !== "manual-restart") {
283
+ await sleep(300);
284
+ const recheck = readBotHealth(deps.paths, Date.now());
285
+ const recheckFresh = recheck.heartbeatAgeMs !== null && recheck.heartbeatAgeMs <= HEARTBEAT_STALE_MS;
286
+ if (recheck.pidAlive !== false && recheckFresh) {
287
+ const ageSec = Math.round((recheck.heartbeatAgeMs ?? 0) / 1000);
288
+ audit(`杀前复核改判 ok:pid=${pid} 心跳已恢复(年龄 ${ageSec}s),放弃误杀`);
289
+ log(`[supervisor] 杀前复核改判 ok:心跳已恢复(${ageSec}s),放弃杀 pid=${pid}`);
290
+ return { action: "ok", detail: `杀前复核:心跳已恢复,放弃误杀 pid=${pid}`, killedPid: null, spawnedPid: null };
291
+ }
292
+ }
293
+ kill(pid, "SIGTERM");
294
+ const deadline = now + policy.graceMs;
295
+ let alive = isAlive(pid);
296
+ while (alive && Date.now() < deadline) {
297
+ await sleep(250);
298
+ alive = isAlive(pid);
299
+ }
300
+ if (alive) {
301
+ kill(pid, "SIGKILL");
302
+ const hardDeadline = Date.now() + 3000;
303
+ while (alive && Date.now() < hardDeadline) {
304
+ await sleep(250);
305
+ alive = isAlive(pid);
306
+ }
307
+ }
308
+ if (alive) {
309
+ audit(`give-up-kill:pid=${pid} 无法终止(权限/系统级),本次不拉起`);
310
+ return { action: "give-up", detail: `pid=${pid} 无法终止`, killedPid: null, spawnedPid: null };
311
+ }
312
+ killedPid = pid;
313
+ }
314
+ try {
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 {}
328
+ }
329
+ if (cleared.length > 0)
330
+ audit(`清锁:${cleared.join("、")}(${action.reason})`);
331
+ } catch {}
332
+ const spawnedPid = deps.spawn();
333
+ state.restartLog.push(Date.now());
334
+ state.restartLog = state.restartLog.filter((t) => t > Date.now() - policy.windowMs * 2);
335
+ try {
336
+ writeFileSync2(statePath, JSON.stringify(state));
337
+ } catch {
338
+ log("[supervisor] 强度账落盘失败(不影响本次拉起)");
339
+ }
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}` : ""}`;
394
+ audit(killedPid ? `主动杀:${detail}` : `验尸拉新:${detail}`);
395
+ return { action: "restart", detail, killedPid, spawnedPid: respawnPid ?? spawnedPid };
396
+ } finally {
397
+ release();
398
+ }
399
+ }
400
+
401
+ // src/core/bot-control.ts
402
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
403
+ import { dirname as dirname3, join as join4 } from "path";
404
+ import { homedir as homedir3 } from "os";
405
+ import { fileURLToPath } from "url";
406
+
407
+ // src/core/bot-launcher.ts
408
+ import { spawn, spawnSync } from "child_process";
409
+ import { existsSync as existsSync3, readFileSync as readFileSync3, statSync as statSync4 } from "fs";
410
+ import { join as join3, dirname as dirname2, isAbsolute } from "path";
411
+ import { homedir as homedir2 } from "os";
412
+ function resolveRuntime(probe = defaultProbe) {
413
+ if (resolveBunCommand(probe))
414
+ return "bun";
415
+ if (probe("node"))
416
+ return "node";
417
+ return null;
418
+ }
419
+ function isExecutable(p) {
420
+ try {
421
+ const st = statSync4(p);
422
+ return st.isFile() && (process.platform === "win32" || (st.mode & 73) !== 0);
423
+ } catch {
424
+ return false;
425
+ }
426
+ }
427
+ function locateOnPath(cmd, pathEnv = process.env.PATH ?? process.env.Path ?? "") {
428
+ if (isAbsolute(cmd))
429
+ return isExecutable(cmd) ? cmd : null;
430
+ const isWin = process.platform === "win32";
431
+ for (const dir of pathEnv.split(isWin ? ";" : ":")) {
432
+ if (!dir)
433
+ continue;
434
+ const base = isWin && !/\.[a-z]+$/i.test(cmd) ? `${cmd}.exe` : cmd;
435
+ const full = join3(dir, base);
436
+ if (isExecutable(full))
437
+ return full;
438
+ }
439
+ if (isWin)
440
+ return resolveThroughShim(cmd, pathEnv);
441
+ return null;
442
+ }
443
+ var SHIM_PATTERN_LINE = /%~?dp0%?\\?([^"\n]+?\.exe)/;
444
+ var SHIM_PATTERN_ABS = /([A-Za-z]:\\[^\n"]+?\.exe)/;
445
+ function resolveThroughShim(bare, pathEnv = process.env.PATH ?? process.env.Path ?? "") {
446
+ for (const dir of pathEnv.split(";")) {
447
+ if (!dir)
448
+ continue;
449
+ for (const ext of [".cmd", ".bat"]) {
450
+ const shimPath = join3(dir, bare + ext);
451
+ let text;
452
+ try {
453
+ text = readFileSync3(shimPath, "utf-8");
454
+ } catch {
455
+ continue;
456
+ }
457
+ const rel = SHIM_PATTERN_LINE.exec(text);
458
+ if (rel) {
459
+ const full = join3(dir, rel[1]);
460
+ if (isExecutable(full))
461
+ return full;
462
+ }
463
+ const abs = SHIM_PATTERN_ABS.exec(text);
464
+ if (abs) {
465
+ const full = abs[1];
466
+ if (isExecutable(full))
467
+ return full;
468
+ }
469
+ }
470
+ }
471
+ return null;
472
+ }
473
+ function bunCandidates() {
474
+ if (process.platform === "win32") {
475
+ const appdata = process.env.APPDATA || join3(homedir2(), "AppData", "Roaming");
476
+ return [
477
+ join3(appdata, "npm", "node_modules", "bun", "bin", "bun.exe"),
478
+ join3(homedir2(), ".bun", "bin", "bun.exe"),
479
+ "bun",
480
+ "bun.exe"
481
+ ];
482
+ }
483
+ return ["/usr/local/bin/bun", "/opt/homebrew/bin/bun", join3(homedir2(), ".bun", "bin", "bun"), "bun"];
484
+ }
485
+ function resolveBunCommand(probe = defaultProbe) {
486
+ if (probe !== defaultProbe) {
487
+ for (const c of bunCandidates()) {
488
+ if (!probe(c))
489
+ continue;
490
+ if (isAbsolute(c))
491
+ return c;
492
+ return locateOnPath(c) ?? resolveThroughShim(c) ?? null;
493
+ }
494
+ return null;
495
+ }
496
+ for (const c of bunCandidates()) {
497
+ const full = locateOnPath(c) ?? (isAbsolute(c) ? null : resolveThroughShim(c));
498
+ if (full)
499
+ return full;
500
+ }
501
+ return null;
502
+ }
503
+ function defaultProbe(cmd) {
504
+ try {
505
+ const r = spawnSync(cmd, ["--version"], { stdio: "ignore", windowsHide: true });
506
+ return r.status === 0;
507
+ } catch {
508
+ return false;
509
+ }
510
+ }
511
+ function resolveRuntimeCommand(runtime) {
512
+ const cmd = runtime === "bun" ? resolveBunCommand() : locateOnPath("node");
513
+ if (!cmd)
514
+ throw new Error(`未找到 ${runtime} 可执行体(全路径解析失败),拒绝生成裸名拉起计划`);
515
+ return cmd;
516
+ }
517
+ function buildLaunchPlan(runtime, entry, logPath) {
518
+ const CONFIG_KEY = [/^QQ_/, /^OPENCODE_/, /^ALLOWED_USERS$/];
519
+ const inherited = {};
520
+ for (const [k, v] of Object.entries(process.env)) {
521
+ if (v === undefined)
522
+ continue;
523
+ if (CONFIG_KEY.some((r) => r.test(k)))
524
+ continue;
525
+ inherited[k] = v;
526
+ }
527
+ const env = {
528
+ ...inherited,
529
+ QQ_INSTANCE_LOCK: "try",
530
+ ...logPath ? { QQ_LOG_FILE: logPath } : {}
531
+ };
532
+ if (runtime === "bun") {
533
+ return { command: resolveRuntimeCommand("bun"), args: ["run", entry], env };
534
+ }
535
+ return { command: resolveRuntimeCommand("node"), args: [entry], env };
536
+ }
537
+ function botLogPath() {
538
+ return join3(homedir2(), ".openqq", "openqq.log");
539
+ }
540
+ function spawnBotDetached(plan) {
541
+ const child = spawn(plan.command, plan.args, {
542
+ detached: true,
543
+ stdio: "ignore",
544
+ env: plan.env,
545
+ windowsHide: true,
546
+ shell: false
547
+ });
548
+ child.unref();
549
+ if (typeof child.pid !== "number")
550
+ throw new Error("spawn 未返回 pid");
551
+ return child.pid;
552
+ }
553
+
554
+ // src/core/bot-control.ts
555
+ function resolveInstalledBotEntry(fromUrl, exists = existsSync4) {
556
+ const here = dirname3(fileURLToPath(fromUrl));
557
+ const candidates = [
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")
562
+ ];
563
+ for (const c of candidates)
564
+ if (exists(c))
565
+ return c;
566
+ return null;
567
+ }
568
+ function readAppId(envPath = join4(homedir3(), ".openqq", ".env")) {
569
+ let botsRaw = null;
570
+ try {
571
+ for (const line of readFileSync4(envPath, "utf-8").split(`
572
+ `)) {
573
+ const t = line.trim();
574
+ if (!t || t.startsWith("#"))
575
+ continue;
576
+ const eq = t.indexOf("=");
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();
587
+ }
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
+ }
597
+ return null;
598
+ }
599
+ function startBot(fromUrl, log = () => {}) {
600
+ const entry = resolveInstalledBotEntry(fromUrl);
601
+ if (!entry)
602
+ throw new Error("未找到 bot 入口(dist/openqq-bot.js 或 src/index.ts)——安装不完整");
603
+ const runtime = resolveRuntime();
604
+ if (!runtime)
605
+ throw new Error("未找到 bun/node 运行时");
606
+ const plan = buildLaunchPlan(runtime, entry, botLogPath());
607
+ const pid = spawnBotDetached(plan);
608
+ log(`[bot-control] 已拉起 pid=${pid}(runtime=${runtime},entry=${entry})`);
609
+ return pid;
610
+ }
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
+
639
+ // src/cli/notify.ts
640
+ import { existsSync as existsSync8, readFileSync as readFileSync9 } from "node:fs";
641
+
642
+ // src/core/storage.ts
643
+ import { homedir as homedir5 } from "os";
644
+ import { join as join6 } from "path";
645
+ var LEGACY_ROOT = join6(homedir5(), ".openqq");
646
+ function storageRoot(appId) {
647
+ const base = (process.env.QQ_DATA_DIR ?? "").trim() || LEGACY_ROOT;
648
+ return appId ? join6(base, "roles", appId) : base;
649
+ }
650
+ function storageFile(name, appId) {
651
+ return join6(storageRoot(appId), name);
652
+ }
653
+
654
+ // src/core/outbox.ts
655
+ import {
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
665
+ } from "node:fs";
666
+ import { dirname as dirname4 } from "node:path";
667
+ import { randomUUID } from "node:crypto";
668
+ var OUTBOX_SENT_RETENTION_MS = 24 * 60 * 60 * 1000;
669
+ var OUTBOX_SENT_RETENTION_LIMIT = 20;
670
+ var OUTBOX_DEFAULT_RETRY_BASE_MS = 1000;
671
+ var OUTBOX_DEFAULT_RETRY_MAX_MS = 60000;
672
+ var DEFAULT_POLL_INTERVAL_MS = 1000;
673
+ var DEFAULT_LEASE_MS = 30000;
674
+ var DEFAULT_LOCK_WAIT_MS = 5000;
675
+ var DEFAULT_LOCK_STALE_MS = 30000;
676
+ var sleepArray = new Int32Array(new SharedArrayBuffer(4));
677
+ function nonNegative(value, fallback, name) {
678
+ const resolved = value ?? fallback;
679
+ if (!Number.isFinite(resolved) || resolved < 0)
680
+ throw new Error(`${name} 必须是 >= 0 的有限数`);
681
+ return resolved;
682
+ }
683
+ function positive(value, fallback, name) {
684
+ const resolved = nonNegative(value, fallback, name);
685
+ if (resolved === 0)
686
+ throw new Error(`${name} 必须 > 0`);
687
+ return resolved;
688
+ }
689
+ function errorText(error) {
690
+ return error instanceof Error ? error.message : String(error);
691
+ }
692
+ function jsonSnapshot(value, label) {
693
+ const encoded = JSON.stringify(value);
694
+ if (encoded === undefined)
695
+ throw new Error(`Outbox ${label} 必须是可 JSON 序列化的值`);
696
+ return JSON.parse(encoded);
697
+ }
698
+ function delay(ms) {
699
+ return new Promise((resolve) => setTimeout(resolve, ms));
700
+ }
701
+ function atomicWrite(filePath, document) {
702
+ mkdirSync2(dirname4(filePath), { recursive: true });
703
+ const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
704
+ try {
705
+ writeFileSync4(temporary, JSON.stringify(document, null, 2), { mode: 384 });
706
+ renameSync2(temporary, filePath);
707
+ } catch (error) {
708
+ try {
709
+ unlinkSync3(temporary);
710
+ } catch {}
711
+ throw error;
712
+ }
713
+ }
714
+ function readDocument(filePath, now) {
715
+ if (!existsSync5(filePath))
716
+ return { version: 1, entries: [] };
717
+ const raw = JSON.parse(readFileSync6(filePath, "utf8"));
718
+ if (Array.isArray(raw)) {
719
+ return { version: 1, entries: pruneOutboxEntries(raw, now) };
720
+ }
721
+ if (typeof raw !== "object" || raw === null || raw.version !== 1 || !Array.isArray(raw.entries)) {
722
+ throw new Error(`Outbox 文件格式无效: ${filePath}`);
723
+ }
724
+ const entries = raw.entries;
725
+ return { version: 1, entries: pruneOutboxEntries(entries, now) };
726
+ }
727
+ function pruneOutboxEntries(entries, now = Date.now()) {
728
+ const indexed = entries.map((entry, index) => ({ entry, index }));
729
+ const retainedSent = new Set(indexed.filter(({ entry }) => entry.state === "sent" && now - entry.updatedAt <= OUTBOX_SENT_RETENTION_MS).sort((a, b) => b.entry.updatedAt - a.entry.updatedAt || b.index - a.index).slice(0, OUTBOX_SENT_RETENTION_LIMIT).map(({ index }) => index));
730
+ return indexed.filter(({ entry, index }) => entry.state !== "sent" || retainedSent.has(index)).sort((a, b) => a.entry.createdAt - b.entry.createdAt || a.index - b.index).map(({ entry }) => entry);
731
+ }
732
+ function createOutbox(options = {}) {
733
+ const filePath = options.filePath ?? process.env.QQ_OUTBOX_FILE ?? storageFile("outbox.json");
734
+ const pollIntervalMs = nonNegative(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, "pollIntervalMs");
735
+ const retryBaseMs = nonNegative(options.retryBaseMs, OUTBOX_DEFAULT_RETRY_BASE_MS, "retryBaseMs");
736
+ const retryMaxMs = nonNegative(options.retryMaxMs, OUTBOX_DEFAULT_RETRY_MAX_MS, "retryMaxMs");
737
+ const leaseMs = positive(options.leaseMs, DEFAULT_LEASE_MS, "leaseMs");
738
+ const lockWaitMs = positive(options.lockWaitMs, DEFAULT_LOCK_WAIT_MS, "lockWaitMs");
739
+ const lockStaleMs = positive(options.lockStaleMs, DEFAULT_LOCK_STALE_MS, "lockStaleMs");
740
+ const owner = `${process.pid}:${randomUUID()}`;
741
+ const handlers = new Map;
742
+ const inFlight = new Map;
743
+ const automatic = new Set;
744
+ let timer;
745
+ let stopped = false;
746
+ let flushing;
747
+ function withLock(fn) {
748
+ mkdirSync2(dirname4(filePath), { recursive: true });
749
+ const lockPath = `${filePath}.lock`;
750
+ const token = `${owner}:${Date.now()}:${randomUUID()}`;
751
+ const deadline = Date.now() + lockWaitMs;
752
+ for (;; ) {
753
+ try {
754
+ const fd = openSync2(lockPath, "wx", 384);
755
+ try {
756
+ writeFileSync4(fd, token);
757
+ } finally {
758
+ closeSync2(fd);
759
+ }
760
+ break;
761
+ } catch (error) {
762
+ try {
763
+ if (Date.now() - statSync5(lockPath).mtimeMs > lockStaleMs)
764
+ unlinkSync3(lockPath);
765
+ } catch {}
766
+ if (Date.now() >= deadline)
767
+ throw new Error(`Outbox 锁等待超时: ${errorText(error)}`);
768
+ Atomics.wait(sleepArray, 0, 0, 10);
769
+ }
770
+ }
771
+ try {
772
+ return fn();
773
+ } finally {
774
+ try {
775
+ if (readFileSync6(lockPath, "utf8") === token)
776
+ unlinkSync3(lockPath);
777
+ } catch {}
778
+ }
779
+ }
780
+ function mutate(fn) {
781
+ return withLock(() => {
782
+ const document = readDocument(filePath, Date.now());
783
+ const result = fn(document.entries);
784
+ document.entries = pruneOutboxEntries(document.entries);
785
+ atomicWrite(filePath, document);
786
+ return result;
787
+ });
788
+ }
789
+ function clone(entry) {
790
+ return JSON.parse(JSON.stringify(entry));
791
+ }
792
+ function clearLease(entry) {
793
+ delete entry.leaseOwner;
794
+ delete entry.leaseUntil;
795
+ }
796
+ function transitionRecovered(entry, now, maxAttempts) {
797
+ if (entry.state !== "sending")
798
+ return false;
799
+ const exhausted = maxAttempts !== undefined && entry.attempts >= maxAttempts;
800
+ entry.state = exhausted ? "failed" : "pending";
801
+ entry.updatedAt = now;
802
+ entry.nextAttemptAt = now;
803
+ entry.lastError = exhausted ? `${entry.lastError ? `${entry.lastError}; ` : ""}崩溃恢复后已达到 maxAttempts=${maxAttempts}` : "进程在 sending 期间退出,发送结果未知;按至少一次语义恢复";
804
+ clearLease(entry);
805
+ return true;
806
+ }
807
+ async function recover(recoverOptions = {}) {
808
+ const now = Date.now();
809
+ return mutate((entries) => {
810
+ const recovered = [];
811
+ const exhausted = [];
812
+ for (const entry of entries) {
813
+ if (entry.state !== "sending")
814
+ continue;
815
+ if (inFlight.has(entry.id) && entry.leaseOwner?.startsWith(`${owner}:`))
816
+ continue;
817
+ const expired = entry.leaseUntil === undefined || entry.leaseUntil <= now;
818
+ if (!recoverOptions.ignoreLeases && !expired)
819
+ continue;
820
+ transitionRecovered(entry, now, recoverOptions.maxAttempts);
821
+ const snapshot = clone(entry);
822
+ if (snapshot.state === "failed")
823
+ exhausted.push(snapshot);
824
+ else
825
+ recovered.push(snapshot);
826
+ }
827
+ return { recovered, exhausted };
828
+ });
829
+ }
830
+ async function dispatchInternal(id, dispatchOptions) {
831
+ const handlerlessSnapshot = readDocument(filePath, Date.now()).entries.find((entry) => entry.id === id);
832
+ if (!handlerlessSnapshot)
833
+ return null;
834
+ const handler = handlers.get(handlerlessSnapshot.kind);
835
+ if (!handler)
836
+ return clone(handlerlessSnapshot);
837
+ const now = Date.now();
838
+ const token = `${owner}:${randomUUID()}`;
839
+ const claimed = withLock(() => {
840
+ const document = readDocument(filePath, now);
841
+ const entry = document.entries.find((candidate) => candidate.id === id);
842
+ if (!entry)
843
+ return { entry: null };
844
+ if (entry.state === "sent")
845
+ return { entry: clone(entry) };
846
+ if (entry.state === "sending" && entry.leaseUntil !== undefined && entry.leaseUntil > now) {
847
+ return { entry: null };
848
+ }
849
+ if ((entry.state === "pending" || entry.state === "failed" || entry.state === "sending") && !dispatchOptions.force && entry.nextAttemptAt > now) {
850
+ return { entry: clone(entry) };
851
+ }
852
+ const maxAttempts = dispatchOptions.maxAttempts;
853
+ if (maxAttempts !== undefined && entry.attempts >= maxAttempts) {
854
+ if (entry.state !== "failed") {
855
+ entry.state = "failed";
856
+ entry.updatedAt = now;
857
+ clearLease(entry);
858
+ atomicWrite(filePath, document);
859
+ }
860
+ return { entry: clone(entry) };
861
+ }
862
+ entry.state = "sending";
863
+ entry.attempts += 1;
864
+ entry.updatedAt = now;
865
+ entry.leaseOwner = token;
866
+ entry.leaseUntil = now + leaseMs;
867
+ delete entry.lastError;
868
+ atomicWrite(filePath, document);
869
+ return { entry: clone(entry), token };
870
+ });
871
+ if (!claimed.entry || !("token" in claimed))
872
+ return claimed.entry;
873
+ try {
874
+ const receipt = await handler(clone(claimed.entry));
875
+ const persistedReceipt = receipt === undefined ? null : jsonSnapshot(receipt, "receipt");
876
+ return mutate((entries) => {
877
+ const current = entries.find((entry) => entry.id === id);
878
+ if (!current || current.leaseOwner !== token)
879
+ return current ? clone(current) : null;
880
+ const completedAt = Date.now();
881
+ current.state = "sent";
882
+ current.updatedAt = completedAt;
883
+ current.receipt = persistedReceipt;
884
+ delete current.lastError;
885
+ clearLease(current);
886
+ return clone(current);
887
+ });
888
+ } catch (error) {
889
+ const failed = mutate((entries) => {
890
+ const current = entries.find((entry) => entry.id === id);
891
+ if (!current || current.leaseOwner !== token)
892
+ return current ? clone(current) : null;
893
+ const failedAt = Date.now();
894
+ current.state = "failed";
895
+ current.updatedAt = failedAt;
896
+ current.lastError = errorText(error);
897
+ current.nextAttemptAt = failedAt + Math.min(retryMaxMs, retryBaseMs * 2 ** Math.max(0, current.attempts - 1));
898
+ clearLease(current);
899
+ return clone(current);
900
+ });
901
+ if (automatic.has(id))
902
+ return failed;
903
+ throw error;
904
+ }
905
+ }
906
+ function dispatch(id, dispatchOptions = {}) {
907
+ const existing = inFlight.get(id);
908
+ if (existing)
909
+ return existing;
910
+ const promise = dispatchInternal(id, dispatchOptions).finally(() => {
911
+ if (inFlight.get(id) === promise)
912
+ inFlight.delete(id);
913
+ });
914
+ inFlight.set(id, promise);
915
+ return promise;
916
+ }
917
+ async function flush(flushOptions = {}) {
918
+ if (flushing)
919
+ return flushing;
920
+ const run = (async () => {
921
+ const results = new Map;
922
+ for (;; ) {
923
+ await recover({ maxAttempts: flushOptions.maxAttempts });
924
+ const entries = readDocument(filePath, Date.now()).entries;
925
+ const candidates = entries.filter((entry) => {
926
+ if (entry.state !== "pending" && entry.state !== "failed")
927
+ return false;
928
+ if (!handlers.has(entry.kind))
929
+ return false;
930
+ if (flushOptions.maxAttempts !== undefined && entry.attempts >= flushOptions.maxAttempts)
931
+ return false;
932
+ return flushOptions.force || flushOptions.wait || entry.nextAttemptAt <= Date.now();
933
+ });
934
+ const settled = await Promise.all(candidates.map(async (entry) => {
935
+ const result = await dispatch(entry.id, flushOptions);
936
+ if (result)
937
+ results.set(entry.id, result);
938
+ return result;
939
+ }));
940
+ if (!flushOptions.wait)
941
+ break;
942
+ const after = readDocument(filePath, Date.now()).entries;
943
+ const active = after.filter((entry) => (entry.state === "pending" || entry.state === "failed") && handlers.has(entry.kind) && (flushOptions.maxAttempts === undefined || entry.attempts < flushOptions.maxAttempts));
944
+ const waitingLocal = after.some((entry) => entry.state === "sending" && inFlight.has(entry.id));
945
+ if (active.length === 0 && !waitingLocal)
946
+ break;
947
+ if (settled.length === 0 && !waitingLocal) {
948
+ const next = active.reduce((minimum, entry) => Math.min(minimum, entry.nextAttemptAt), Number.POSITIVE_INFINITY);
949
+ if (Number.isFinite(next))
950
+ await delay(Math.max(1, next - Date.now()));
951
+ else
952
+ break;
953
+ } else {
954
+ await delay(1);
955
+ }
956
+ }
957
+ return [...results.values()];
958
+ })();
959
+ flushing = run;
960
+ try {
961
+ return await run;
962
+ } finally {
963
+ if (flushing === run)
964
+ flushing = undefined;
965
+ }
966
+ }
967
+ async function drain() {
968
+ while (inFlight.size > 0) {
969
+ const pending = [...inFlight.values()];
970
+ const outcomes = await Promise.allSettled(pending);
971
+ const rejection = outcomes.find((outcome) => outcome.status === "rejected");
972
+ if (rejection)
973
+ throw rejection.reason;
974
+ }
975
+ }
976
+ return {
977
+ filePath,
978
+ register(kind, handler) {
979
+ if (!kind)
980
+ throw new Error("Outbox kind 不能为空");
981
+ handlers.set(kind, handler);
982
+ return () => {
983
+ if (handlers.get(kind) === handler)
984
+ handlers.delete(kind);
985
+ };
986
+ },
987
+ async enqueue(input) {
988
+ if (!input.kind)
989
+ throw new Error("Outbox kind 不能为空");
990
+ if (input.payload === undefined)
991
+ throw new Error("Outbox payload 必须是 JSON 值,不能为 undefined");
992
+ if (input.nextAttemptAt !== undefined && !Number.isFinite(input.nextAttemptAt)) {
993
+ throw new Error("Outbox nextAttemptAt 必须是有限时间戳");
994
+ }
995
+ const persistedCtx = jsonSnapshot(input.ctx, "ctx");
996
+ const persistedPayload = jsonSnapshot(input.payload, "payload");
997
+ const now = Date.now();
998
+ const id = input.id ?? randomUUID();
999
+ const entry = mutate((entries) => {
1000
+ const existing = entries.find((candidate) => candidate.id === id);
1001
+ if (existing)
1002
+ return clone(existing);
1003
+ const created = {
1004
+ id,
1005
+ kind: input.kind,
1006
+ ctx: persistedCtx,
1007
+ payload: persistedPayload,
1008
+ ...input.sessionId !== undefined ? { sessionId: input.sessionId } : {},
1009
+ ...input.turnId !== undefined ? { turnId: input.turnId } : {},
1010
+ state: "pending",
1011
+ attempts: 0,
1012
+ createdAt: now,
1013
+ updatedAt: now,
1014
+ nextAttemptAt: input.nextAttemptAt ?? now
1015
+ };
1016
+ entries.push(created);
1017
+ return clone(created);
1018
+ });
1019
+ automatic.add(id);
1020
+ dispatch(id).finally(() => automatic.delete(id)).catch(() => {});
1021
+ return entry;
1022
+ },
1023
+ dispatch,
1024
+ recover,
1025
+ flush,
1026
+ async start(startOptions = {}) {
1027
+ stopped = false;
1028
+ if (startOptions.recover !== false)
1029
+ await recover({ maxAttempts: startOptions.maxAttempts });
1030
+ if (pollIntervalMs === 0 || timer)
1031
+ return;
1032
+ timer = setInterval(() => {
1033
+ if (stopped)
1034
+ return;
1035
+ flush({ maxAttempts: startOptions.maxAttempts }).catch(() => {});
1036
+ }, pollIntervalMs);
1037
+ timer.unref?.();
1038
+ flush({ maxAttempts: startOptions.maxAttempts }).catch(() => {});
1039
+ },
1040
+ stop() {
1041
+ stopped = true;
1042
+ if (timer)
1043
+ clearInterval(timer);
1044
+ timer = undefined;
1045
+ },
1046
+ drain,
1047
+ async list() {
1048
+ return readDocument(filePath, Date.now()).entries.map((entry) => clone(entry));
1049
+ },
1050
+ async get(id) {
1051
+ const entry = readDocument(filePath, Date.now()).entries.find((candidate) => candidate.id === id);
1052
+ return entry ? clone(entry) : undefined;
1053
+ }
1054
+ };
1055
+ }
1056
+
1057
+ // src/config.ts
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");
1114
+ function loadEnvFile(path) {
1115
+ const content = readFileSync8(path, "utf-8");
1116
+ for (const line of content.split(`
1117
+ `)) {
1118
+ const trimmed = line.trim();
1119
+ if (!trimmed || trimmed.startsWith("#"))
1120
+ continue;
1121
+ const eqIdx = trimmed.indexOf("=");
1122
+ if (eqIdx < 0)
1123
+ continue;
1124
+ const key = trimmed.slice(0, eqIdx).trim();
1125
+ const val = trimmed.slice(eqIdx + 1).trim();
1126
+ if (!process.env[key]) {
1127
+ process.env[key] = val;
1128
+ }
1129
+ }
1130
+ }
1131
+
1132
+ // src/core/notify-sink.ts
1133
+ function resolveNotifyRecipients(configured, explicit) {
1134
+ const users = [...configured];
1135
+ if (explicit)
1136
+ return users.includes(explicit) ? explicit : "";
1137
+ return users.length === 1 ? users[0] : "";
1138
+ }
1139
+ function defaultOutboxPath() {
1140
+ return storageFile("outbox.json");
1141
+ }
1142
+
1143
+ // src/cli/notify.ts
1144
+ var NOTIFY_DEFAULT_MAX_CHARS = 1500;
1145
+ function parseArgs(argv) {
1146
+ const parsed = { maxChars: NOTIFY_DEFAULT_MAX_CHARS, dryRun: false, json: false, help: false };
1147
+ for (let i = 0;i < argv.length; i++) {
1148
+ const a = argv[i];
1149
+ const next = argv[i + 1];
1150
+ switch (a) {
1151
+ case "--text":
1152
+ parsed.text = next;
1153
+ i++;
1154
+ break;
1155
+ case "--file":
1156
+ parsed.filePath = next;
1157
+ i++;
1158
+ break;
1159
+ case "--stdin":
1160
+ parsed.stdin = true;
1161
+ break;
1162
+ case "--user":
1163
+ parsed.user = next;
1164
+ i++;
1165
+ break;
1166
+ case "--id":
1167
+ parsed.id = next;
1168
+ i++;
1169
+ break;
1170
+ case "--max-chars":
1171
+ parsed.maxChars = Number(next);
1172
+ i++;
1173
+ break;
1174
+ case "--ttl-hours":
1175
+ parsed.ttlHours = Number(next);
1176
+ i++;
1177
+ break;
1178
+ case "--dry-run":
1179
+ parsed.dryRun = true;
1180
+ break;
1181
+ case "--json":
1182
+ parsed.json = true;
1183
+ break;
1184
+ case "--help":
1185
+ case "-h":
1186
+ parsed.help = true;
1187
+ i++;
1188
+ break;
1189
+ default:
1190
+ throw new Error(`未知参数:${a}(用法:openqq notify --text "…" | --file <p> | --stdin)`);
1191
+ }
1192
+ }
1193
+ if (!parsed.help && !parsed.text && !parsed.filePath && !parsed.stdin) {
1194
+ throw new Error("必须提供正文来源:--text / --file / --stdin 三选一");
1195
+ }
1196
+ if (!Number.isFinite(parsed.maxChars) || parsed.maxChars < 0) {
1197
+ throw new Error("--max-chars 必须是 >= 0 的有限数(0=不截断)");
1198
+ }
1199
+ return parsed;
1200
+ }
1201
+ function resolveUser(envAllowed, explicit) {
1202
+ return resolveNotifyRecipients(envAllowed, explicit);
1203
+ }
1204
+ function readBody(parsed) {
1205
+ if (parsed.text !== undefined)
1206
+ return parsed.text;
1207
+ if (parsed.filePath !== undefined) {
1208
+ if (parsed.filePath === "-")
1209
+ return readFileSync9(0, "utf8");
1210
+ if (!existsSync8(parsed.filePath))
1211
+ throw new Error(`--file 不存在:${parsed.filePath}`);
1212
+ return readFileSync9(parsed.filePath, "utf8");
1213
+ }
1214
+ if (parsed.stdin)
1215
+ return readFileSync9(0, "utf8");
1216
+ return "";
1217
+ }
1218
+ async function runNotifyCli(argv, options = {}) {
1219
+ const now = options.now ?? Date.now();
1220
+ const parsed = parseArgs(argv);
1221
+ if (parsed.help) {
1222
+ const help = [
1223
+ '用法:openqq notify --text "…" | --file <路径> | --stdin',
1224
+ " --user <openid> 收件人;缺省取 ALLOWED_USERS 唯一项(多用户必须显式指定)",
1225
+ " --id <key> 幂等键(同 key 不重复投递)",
1226
+ " --max-chars <n> 截断上限,默认 1500,0 不截断",
1227
+ " --ttl-hours <n> 队列等待上限,默认 24(env QQ_NOTIFY_TTL_HOURS 兜底)",
1228
+ " --dry-run / --json 不入队 / 机器可读输出"
1229
+ ].join(`
1230
+ `);
1231
+ console.log(help);
1232
+ return { ok: true, queued: false, id: "", user: "", chars: 0, truncated: false, dryRun: true, json: parsed.json, reason: "help" };
1233
+ }
1234
+ applyConfigOverlay();
1235
+ if (!options.env && existsSync8(ENV_FILE))
1236
+ loadEnvFile(ENV_FILE);
1237
+ const allowedUsers = options.env ? [...options.env.allowedUsers] : String(process.env.ALLOWED_USERS ?? "").split(/[,\s]+/).filter(Boolean);
1238
+ const user = resolveUser(allowedUsers, parsed.user);
1239
+ if (!user) {
1240
+ throw new Error(allowedUsers.length === 0 ? "ALLOWED_USERS 为空——fail-closed 不允许无名单入队(先在 ~/.openqq/.env 配置)" : parsed.user ? `收件人不在名单:${parsed.user}(ALLOWED_USERS 共 ${allowedUsers.length} 项,--user 必须精确命中;请核对 openid)` : "多用户名单必须用 --user <openid> 显式指定收件人");
1241
+ }
1242
+ const raw = readBody(parsed);
1243
+ const max = parsed.maxChars;
1244
+ const content = max === 0 ? raw : raw.length > max ? `${raw.slice(0, max)}…` : raw;
1245
+ const id = parsed.id || `notify-${now.toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
1246
+ const filePath = options.filePath ?? defaultOutboxPath();
1247
+ if (parsed.dryRun) {
1248
+ return { ok: true, queued: false, id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: true, json: parsed.json };
1249
+ }
1250
+ const ttlHours = parsed.ttlHours ?? Number(process.env.QQ_NOTIFY_TTL_HOURS ?? 24);
1251
+ const nextAttemptAt = parsed.ttlHours !== undefined && Number.isFinite(ttlHours) && ttlHours > 0 ? now + ttlHours * 60 * 60 * 1000 : now;
1252
+ const outbox = createOutbox({ filePath, pollIntervalMs: 0 });
1253
+ const entry = await outbox.enqueue({
1254
+ ...parsed.id ? { id: parsed.id } : {},
1255
+ kind: "notify",
1256
+ payload: { text: content },
1257
+ ctx: { type: "c2c", userId: user, msgId: "", content: "(openqq notify)", timestamp: String(now) },
1258
+ sessionId: "",
1259
+ nextAttemptAt
1260
+ });
1261
+ return { ok: true, queued: true, id: entry.id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: false, json: parsed.json };
1262
+ }
1263
+
1264
+ // src/cli/watchdog-main.ts
1265
+ var DEFAULT_INTERVAL_MIN = 10;
1266
+ function parseArgs2(argv) {
1267
+ const loop = argv.includes("--loop");
1268
+ const idx = argv.indexOf("--interval-min");
1269
+ const raw = idx >= 0 ? Number(argv[idx + 1]) : Number.NaN;
1270
+ const intervalMin = Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_INTERVAL_MIN;
1271
+ return { loop, intervalMin };
1272
+ }
1273
+ function currentAppId() {
1274
+ return readAppId();
1275
+ }
1276
+ function alert(message) {
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));
1278
+ }
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
+ }
1288
+ const result = await superviseOnce({
1289
+ paths,
1290
+ spawn: () => startBot(import.meta.url, (line) => console.log(line)),
1291
+ log: (line) => console.log(line),
1292
+ alert
1293
+ });
1294
+ console.log(`[supervisor] ${result.action}:${result.detail}`);
1295
+ if (result.action !== "ok")
1296
+ appendWatchdogLog(`[supervisor] ${result.action}:${result.detail}`);
1297
+ }
1298
+ async function main() {
1299
+ const args = parseArgs2(process.argv.slice(2));
1300
+ const appId = currentAppId();
1301
+ if (!appId) {
1302
+ console.error("[watchdog] 未找到任何角色凭据(~/.openqq/.env 缺 QQ_APP_ID/QQ_APP_SECRET 且 QQ_BOTS 无合法角色),无法定位实例锁");
1303
+ process.exit(1);
1304
+ }
1305
+ console.log(`[watchdog] 模式=${args.loop ? `loop/${args.intervalMin}min` : "once"}(监督矩阵:冷却2m/强度3次15m/优雅杀8s)`);
1306
+ await tick(appId);
1307
+ if (!args.loop)
1308
+ return;
1309
+ const timer = setInterval(() => {
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
+ });
1314
+ }, args.intervalMin * 60000);
1315
+ const stop = () => {
1316
+ clearInterval(timer);
1317
+ process.exit(0);
1318
+ };
1319
+ process.once("SIGINT", stop);
1320
+ process.once("SIGTERM", stop);
1321
+ }
1322
+ main().catch((error) => {
1323
+ appendWatchdogLog(`[watchdog] 致命错误: ${error instanceof Error ? error.message : String(error)}`);
1324
+ console.error("[watchdog] 致命错误:", error instanceof Error ? error.message : error);
1325
+ process.exit(1);
1326
+ });