@linjz/opencode-qqbot 0.3.14 → 0.3.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +73 -5
  2. package/bin/openqq.js +34 -0
  3. package/dist/notify-cli.js +593 -0
  4. package/dist/opencode-qqbot-plugin.js +938 -65
  5. package/dist/openqq-bot.js +3585 -717
  6. package/dist/openqq-cli.js +791 -0
  7. package/dist/openqq-watchdog.js +1063 -0
  8. package/package.json +9 -5
  9. package/src/bridge.ts +1338 -157
  10. package/src/cli/notify-main.ts +6 -0
  11. package/src/cli/notify.ts +167 -0
  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 +77 -0
  15. package/src/commands.ts +644 -554
  16. package/src/config.ts +87 -2
  17. package/src/core/bot-control.ts +148 -0
  18. package/src/core/bot-launcher.ts +106 -13
  19. package/src/core/card-approval.ts +20 -9
  20. package/src/core/delivery.ts +145 -54
  21. package/src/core/discovery.ts +22 -4
  22. package/src/core/file-log.ts +35 -3
  23. package/src/core/form-bridge.ts +16 -7
  24. package/src/core/form-journal.ts +4 -4
  25. package/src/core/gateway-state.ts +3 -3
  26. package/src/core/inflight-journal.ts +214 -36
  27. package/src/core/instance-lock.ts +21 -6
  28. package/src/core/linkwatch.ts +3 -4
  29. package/src/core/markdown.ts +117 -0
  30. package/src/core/message-queue.ts +242 -91
  31. package/src/core/mirror.ts +222 -182
  32. package/src/core/notify-sink.ts +93 -0
  33. package/src/core/outbox.ts +10 -9
  34. package/src/core/permission.ts +627 -301
  35. package/src/core/question-form.ts +230 -0
  36. package/src/core/queue-view.ts +661 -0
  37. package/src/core/send-media.ts +32 -0
  38. package/src/core/storage.ts +34 -0
  39. package/src/core/watchdog.ts +513 -0
  40. package/src/core/zombie-reaper.ts +127 -0
  41. package/src/index.ts +140 -52
  42. package/src/opencode/client.ts +206 -27
  43. package/src/opencode/eventstream.ts +94 -12
  44. package/src/opencode/history.ts +4 -2
  45. package/src/opencode/mirror.ts +15 -2
  46. package/src/opencode/sessions.ts +135 -37
  47. package/src/plugin-entry.ts +120 -112
  48. package/src/qq/api.ts +165 -61
  49. package/src/qq/gateway.ts +80 -17
  50. package/src/qq/media.ts +5 -1
  51. package/src/qq/sender.ts +30 -18
  52. package/src/qq/types.ts +7 -0
@@ -0,0 +1,1063 @@
1
+ // src/core/watchdog.ts
2
+ import { readFileSync, statSync, unlinkSync, writeFileSync } from "fs";
3
+ import { join } from "path";
4
+ import { homedir } from "os";
5
+ var HEARTBEAT_STALE_MS = 5 * 60000;
6
+ function botWatchdogPaths(appId) {
7
+ const dir = join(homedir(), ".openqq");
8
+ return { lockPath: join(dir, `openqq-${appId}.lock`), heartbeatPath: join(dir, "heartbeat") };
9
+ }
10
+ function isPidAlive(pid) {
11
+ if (!Number.isInteger(pid) || pid <= 0)
12
+ return false;
13
+ try {
14
+ process.kill(pid, 0);
15
+ return true;
16
+ } catch (error) {
17
+ return error.code === "EPERM";
18
+ }
19
+ }
20
+ function ageOf(path, now) {
21
+ try {
22
+ return Math.max(0, now - statSync(path).mtimeMs);
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+ function readBotHealth(paths, now = Date.now()) {
28
+ const lockAgeMs = ageOf(paths.lockPath, now);
29
+ let lockPid = null;
30
+ if (lockAgeMs !== null) {
31
+ try {
32
+ const raw = JSON.parse(readFileSync(paths.lockPath, "utf-8"));
33
+ if (typeof raw.pid === "number" && Number.isInteger(raw.pid))
34
+ lockPid = raw.pid;
35
+ } catch {}
36
+ }
37
+ return {
38
+ lockPid,
39
+ lockAgeMs,
40
+ pidAlive: lockPid === null ? null : isPidAlive(lockPid),
41
+ heartbeatAgeMs: ageOf(paths.heartbeatPath, now)
42
+ };
43
+ }
44
+ function readEnvField(envPath, key) {
45
+ 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();
56
+ }
57
+ return null;
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+ function appendWatchdogLog(line) {
63
+ try {
64
+ const dir = join(homedir(), ".openqq");
65
+ writeFileSync(join(dir, "watchdog.log"), `${new Date().toISOString()} ${line}
66
+ `, { flag: "a" });
67
+ } catch {}
68
+ }
69
+ var DEFAULT_SUPERVISOR_POLICY = {
70
+ cooldownMs: 2 * 60000,
71
+ maxRestarts: 3,
72
+ windowMs: 15 * 60000,
73
+ graceMs: 8000,
74
+ claimTtlMs: 90000
75
+ };
76
+ function decideSupervise(health, state, now, policy = DEFAULT_SUPERVISOR_POLICY) {
77
+ const staleHeartbeat = health.heartbeatAgeMs !== null && health.heartbeatAgeMs > HEARTBEAT_STALE_MS;
78
+ const needsRestart = health.lockPid === null || health.pidAlive === false || staleHeartbeat;
79
+ if (!needsRestart)
80
+ return { kind: "ok" };
81
+ const windowStart = now - policy.windowMs;
82
+ const recentRestarts = state.restartLog.filter((t) => t > windowStart).length;
83
+ if (recentRestarts >= policy.maxRestarts)
84
+ return { kind: "give-up", restarts: recentRestarts };
85
+ const last = state.restartLog[state.restartLog.length - 1] ?? null;
86
+ if (last !== null && now - last < policy.cooldownMs)
87
+ return { kind: "cooldown", untilMs: last + policy.cooldownMs };
88
+ if (health.lockPid !== null && health.pidAlive !== false && staleHeartbeat) {
89
+ return {
90
+ kind: "grace-kill-spawn",
91
+ killPid: health.lockPid,
92
+ reason: `心跳陈旧 ${Math.round((health.heartbeatAgeMs ?? 0) / 60000)} 分钟(进程活但事件循环无进展)`
93
+ };
94
+ }
95
+ return { kind: "spawn", reason: health.lockPid === null ? "无实例锁(bot 未运行)" : "锁定进程已退出" };
96
+ }
97
+ var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
98
+ var defaultSupervisorKill = (pid, signal) => {
99
+ try {
100
+ process.kill(pid, signal);
101
+ } catch {}
102
+ };
103
+ function readJson(path, fallback) {
104
+ try {
105
+ return { ...fallback, ...JSON.parse(readFileSync(path, "utf-8")) };
106
+ } catch {
107
+ return fallback;
108
+ }
109
+ }
110
+ async function superviseOnce(deps) {
111
+ const policy = deps.policy ?? DEFAULT_SUPERVISOR_POLICY;
112
+ const now = deps.now?.() ?? Date.now();
113
+ const log = deps.log ?? (() => {});
114
+ const sleep = deps.sleep ?? defaultSleep;
115
+ const kill = deps.kill ?? defaultSupervisorKill;
116
+ 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");
119
+ const audit = (line) => {
120
+ if (deps.auditLogPath) {
121
+ try {
122
+ writeFileSync(deps.auditLogPath, `${new Date().toISOString()} ${line}
123
+ `, { flag: "a" });
124
+ return;
125
+ } catch {}
126
+ }
127
+ appendWatchdogLog(line);
128
+ };
129
+ const claim = readJson(claimPath, { pid: 0, ts: 0 });
130
+ if (claim.ts && now - claim.ts < policy.claimTtlMs && claim.pid !== process.pid) {
131
+ return { action: "yield", detail: `监督者 pid=${claim.pid} 持锁中`, killedPid: null, spawnedPid: null };
132
+ }
133
+ try {
134
+ writeFileSync(claimPath, JSON.stringify({ pid: process.pid, ts: now }));
135
+ } catch {
136
+ return { action: "yield", detail: "认领锁不可写", killedPid: null, spawnedPid: null };
137
+ }
138
+ const release = () => {
139
+ try {
140
+ writeFileSync(claimPath, JSON.stringify({ pid: 0, ts: 0 }));
141
+ } catch {}
142
+ };
143
+ try {
144
+ const health = readBotHealth(deps.paths, now);
145
+ const state = readJson(statePath, { restartLog: [] });
146
+ let action = decideSupervise(health, state, now, policy);
147
+ if (deps.request === "manual-restart" && action.kind === "ok") {
148
+ const windowStart = now - policy.windowMs;
149
+ const recentRestarts = state.restartLog.filter((t) => t > windowStart).length;
150
+ if (recentRestarts >= policy.maxRestarts) {
151
+ return {
152
+ action: "give-up",
153
+ detail: `15 分钟内已重启 ${recentRestarts} 次(监督强度上限),人工重启亦被拦截,请排查根因`,
154
+ killedPid: null,
155
+ spawnedPid: null
156
+ };
157
+ }
158
+ const last = state.restartLog[state.restartLog.length - 1] ?? null;
159
+ if (last !== null && now - last < policy.cooldownMs) {
160
+ return { action: "cooldown", detail: `距上次重启不足 ${Math.round(policy.cooldownMs / 1000)}s(冷却期),人工重启跳过`, killedPid: null, spawnedPid: null };
161
+ }
162
+ action = health.lockPid !== null && health.pidAlive !== false ? { kind: "grace-kill-spawn", killPid: health.lockPid, reason: "人工请求重启(openqq restart)" } : { kind: "spawn", reason: "人工请求重启(bot 未运行,直接拉起)" };
163
+ }
164
+ if (action.kind === "ok")
165
+ return { action: "ok", detail: "健康", killedPid: null, spawnedPid: null };
166
+ if (action.kind === "cooldown") {
167
+ log(`[supervisor] 冷却中(上次重启 ${Math.round((now - (action.untilMs - policy.cooldownMs)) / 1000)}s 前),本轮跳过`);
168
+ return { action: "cooldown", detail: "冷却跳过", killedPid: null, spawnedPid: null };
169
+ }
170
+ if (action.kind === "yield") {
171
+ return { action: "yield", detail: action.reason, killedPid: null, spawnedPid: null };
172
+ }
173
+ if (action.kind === "give-up") {
174
+ const message = `⚠️ QQBot 看门狗已放弃:${action.restarts} 次重启/${Math.round(policy.windowMs / 60000)} 分钟仍不健康。继续自动重启没有意义(同因反复死亡),请人工检查 %TEMP%\\opencode 下 bot.out.log 与 ~/.openqq/watchdog.log。`;
175
+ audit(`give-up:${message}`);
176
+ log(`[supervisor] give-up:${action.restarts} 次重启仍异常,停止循环并上报`);
177
+ const lastAlert = state.alertedAt ?? 0;
178
+ if (now - lastAlert > 30 * 60000) {
179
+ try {
180
+ deps.alert?.(message);
181
+ state.alertedAt = now;
182
+ writeFileSync(statePath, JSON.stringify(state));
183
+ } catch {}
184
+ }
185
+ return { action: "give-up", detail: message, killedPid: null, spawnedPid: null };
186
+ }
187
+ let killedPid = null;
188
+ if (action.kind === "grace-kill-spawn" && action.killPid !== process.pid) {
189
+ const pid = action.killPid;
190
+ if (deps.request !== "manual-restart") {
191
+ await sleep(300);
192
+ const recheck = readBotHealth(deps.paths, Date.now());
193
+ const recheckFresh = recheck.heartbeatAgeMs !== null && recheck.heartbeatAgeMs <= HEARTBEAT_STALE_MS;
194
+ if (recheck.pidAlive !== false && recheckFresh) {
195
+ const ageSec = Math.round((recheck.heartbeatAgeMs ?? 0) / 1000);
196
+ audit(`杀前复核改判 ok:pid=${pid} 心跳已恢复(年龄 ${ageSec}s),放弃误杀`);
197
+ log(`[supervisor] 杀前复核改判 ok:心跳已恢复(${ageSec}s),放弃杀 pid=${pid}`);
198
+ return { action: "ok", detail: `杀前复核:心跳已恢复,放弃误杀 pid=${pid}`, killedPid: null, spawnedPid: null };
199
+ }
200
+ }
201
+ kill(pid, "SIGTERM");
202
+ const deadline = now + policy.graceMs;
203
+ let alive = isAlive(pid);
204
+ while (alive && Date.now() < deadline) {
205
+ await sleep(250);
206
+ alive = isAlive(pid);
207
+ }
208
+ if (alive) {
209
+ kill(pid, "SIGKILL");
210
+ const hardDeadline = Date.now() + 3000;
211
+ while (alive && Date.now() < hardDeadline) {
212
+ await sleep(250);
213
+ alive = isAlive(pid);
214
+ }
215
+ }
216
+ if (alive) {
217
+ audit(`give-up-kill:pid=${pid} 无法终止(权限/系统级),本次不拉起`);
218
+ return { action: "give-up", detail: `pid=${pid} 无法终止`, killedPid: null, spawnedPid: null };
219
+ }
220
+ killedPid = pid;
221
+ }
222
+ try {
223
+ if (killedPid !== null || health.lockPid === null || health.pidAlive === false) {
224
+ unlinkSync(deps.paths.lockPath);
225
+ audit(`清锁:${deps.paths.lockPath}(${action.reason})`);
226
+ }
227
+ } catch {}
228
+ const spawnedPid = deps.spawn();
229
+ state.restartLog.push(Date.now());
230
+ state.restartLog = state.restartLog.filter((t) => t > Date.now() - policy.windowMs * 2);
231
+ try {
232
+ writeFileSync(statePath, JSON.stringify(state));
233
+ } catch {
234
+ log("[supervisor] 强度账落盘失败(不影响本次拉起)");
235
+ }
236
+ const detail = `${action.reason};${killedPid ? `已优雅停 pid=${killedPid};` : ""}已拉起 pid=${spawnedPid}`;
237
+ audit(killedPid ? `主动杀:${detail}` : `验尸拉新:${detail}`);
238
+ return { action: "restart", detail, killedPid, spawnedPid };
239
+ } finally {
240
+ release();
241
+ }
242
+ }
243
+
244
+ // 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";
247
+ import { homedir as homedir3 } from "os";
248
+ import { fileURLToPath } from "url";
249
+
250
+ // src/core/bot-launcher.ts
251
+ 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";
254
+ import { homedir as homedir2 } from "os";
255
+ function resolveRuntime(probe = defaultProbe) {
256
+ if (resolveBunCommand(probe))
257
+ return "bun";
258
+ if (probe("node"))
259
+ return "node";
260
+ return null;
261
+ }
262
+ function isExecutable(p) {
263
+ try {
264
+ const st = statSync2(p);
265
+ return st.isFile() && (process.platform === "win32" || (st.mode & 73) !== 0);
266
+ } catch {
267
+ return false;
268
+ }
269
+ }
270
+ function locateOnPath(cmd, pathEnv = process.env.PATH ?? process.env.Path ?? "") {
271
+ if (isAbsolute(cmd))
272
+ return isExecutable(cmd) ? cmd : null;
273
+ const isWin = process.platform === "win32";
274
+ for (const dir of pathEnv.split(isWin ? ";" : ":")) {
275
+ if (!dir)
276
+ continue;
277
+ const base = isWin && !/\.[a-z]+$/i.test(cmd) ? `${cmd}.exe` : cmd;
278
+ const full = join2(dir, base);
279
+ if (isExecutable(full))
280
+ return full;
281
+ }
282
+ if (isWin)
283
+ return resolveThroughShim(cmd, pathEnv);
284
+ return null;
285
+ }
286
+ var SHIM_PATTERN_LINE = /%~?dp0%?\\?([^"\n]+?\.exe)/;
287
+ var SHIM_PATTERN_ABS = /([A-Za-z]:\\[^\n"]+?\.exe)/;
288
+ function resolveThroughShim(bare, pathEnv = process.env.PATH ?? process.env.Path ?? "") {
289
+ for (const dir of pathEnv.split(";")) {
290
+ if (!dir)
291
+ continue;
292
+ for (const ext of [".cmd", ".bat"]) {
293
+ const shimPath = join2(dir, bare + ext);
294
+ let text;
295
+ try {
296
+ text = readFileSync2(shimPath, "utf-8");
297
+ } catch {
298
+ continue;
299
+ }
300
+ const rel = SHIM_PATTERN_LINE.exec(text);
301
+ if (rel) {
302
+ const full = join2(dir, rel[1]);
303
+ if (isExecutable(full))
304
+ return full;
305
+ }
306
+ const abs = SHIM_PATTERN_ABS.exec(text);
307
+ if (abs) {
308
+ const full = abs[1];
309
+ if (isExecutable(full))
310
+ return full;
311
+ }
312
+ }
313
+ }
314
+ return null;
315
+ }
316
+ function bunCandidates() {
317
+ if (process.platform === "win32") {
318
+ const appdata = process.env.APPDATA || join2(homedir2(), "AppData", "Roaming");
319
+ return [
320
+ join2(appdata, "npm", "node_modules", "bun", "bin", "bun.exe"),
321
+ join2(homedir2(), ".bun", "bin", "bun.exe"),
322
+ "bun",
323
+ "bun.exe"
324
+ ];
325
+ }
326
+ return ["/usr/local/bin/bun", "/opt/homebrew/bin/bun", join2(homedir2(), ".bun", "bin", "bun"), "bun"];
327
+ }
328
+ function resolveBunCommand(probe = defaultProbe) {
329
+ if (probe !== defaultProbe) {
330
+ for (const c of bunCandidates()) {
331
+ if (!probe(c))
332
+ continue;
333
+ if (isAbsolute(c))
334
+ return c;
335
+ return locateOnPath(c) ?? resolveThroughShim(c) ?? null;
336
+ }
337
+ return null;
338
+ }
339
+ for (const c of bunCandidates()) {
340
+ const full = locateOnPath(c) ?? (isAbsolute(c) ? null : resolveThroughShim(c));
341
+ if (full)
342
+ return full;
343
+ }
344
+ return null;
345
+ }
346
+ function defaultProbe(cmd) {
347
+ try {
348
+ const r = spawnSync(cmd, ["--version"], { stdio: "ignore", windowsHide: true });
349
+ return r.status === 0;
350
+ } catch {
351
+ return false;
352
+ }
353
+ }
354
+ function resolveRuntimeCommand(runtime) {
355
+ const cmd = runtime === "bun" ? resolveBunCommand() : locateOnPath("node");
356
+ if (!cmd)
357
+ throw new Error(`未找到 ${runtime} 可执行体(全路径解析失败),拒绝生成裸名拉起计划`);
358
+ return cmd;
359
+ }
360
+ function buildLaunchPlan(runtime, entry, logPath) {
361
+ const CONFIG_KEY = [/^QQ_/, /^OPENCODE_/, /^ALLOWED_USERS$/];
362
+ const inherited = {};
363
+ for (const [k, v] of Object.entries(process.env)) {
364
+ if (v === undefined)
365
+ continue;
366
+ if (CONFIG_KEY.some((r) => r.test(k)))
367
+ continue;
368
+ inherited[k] = v;
369
+ }
370
+ const env = {
371
+ ...inherited,
372
+ QQ_INSTANCE_LOCK: "try",
373
+ ...logPath ? { QQ_LOG_FILE: logPath } : {}
374
+ };
375
+ if (runtime === "bun") {
376
+ return { command: resolveRuntimeCommand("bun"), args: ["run", entry], env };
377
+ }
378
+ return { command: resolveRuntimeCommand("node"), args: [entry], env };
379
+ }
380
+ function botLogPath() {
381
+ return join2(homedir2(), ".openqq", "bot.out.log");
382
+ }
383
+ function spawnBotDetached(plan) {
384
+ const child = spawn(plan.command, plan.args, {
385
+ detached: true,
386
+ stdio: "ignore",
387
+ env: plan.env,
388
+ windowsHide: true,
389
+ shell: false
390
+ });
391
+ child.unref();
392
+ if (typeof child.pid !== "number")
393
+ throw new Error("spawn 未返回 pid");
394
+ return child.pid;
395
+ }
396
+
397
+ // src/core/bot-control.ts
398
+ function resolveInstalledBotEntry(fromUrl, exists = existsSync2) {
399
+ const here = dirname2(fileURLToPath(fromUrl));
400
+ 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")
405
+ ];
406
+ for (const c of candidates)
407
+ if (exists(c))
408
+ return c;
409
+ return null;
410
+ }
411
+ function readAppId(envPath = join3(homedir3(), ".openqq", ".env")) {
412
+ try {
413
+ for (const line of readFileSync3(envPath, "utf-8").split(`
414
+ `)) {
415
+ const t = line.trim();
416
+ if (!t || t.startsWith("#"))
417
+ continue;
418
+ const eq = t.indexOf("=");
419
+ if (eq > 0 && t.slice(0, eq).trim() === "QQ_APP_ID")
420
+ return t.slice(eq + 1).trim() || null;
421
+ }
422
+ } catch {}
423
+ return null;
424
+ }
425
+ function startBot(fromUrl, log = () => {}) {
426
+ const entry = resolveInstalledBotEntry(fromUrl);
427
+ if (!entry)
428
+ throw new Error("未找到 bot 入口(dist/openqq-bot.js 或 src/index.ts)——安装不完整");
429
+ const runtime = resolveRuntime();
430
+ if (!runtime)
431
+ throw new Error("未找到 bun/node 运行时");
432
+ const plan = buildLaunchPlan(runtime, entry, botLogPath());
433
+ const pid = spawnBotDetached(plan);
434
+ log(`[bot-control] 已拉起 pid=${pid}(runtime=${runtime},entry=${entry})`);
435
+ return pid;
436
+ }
437
+
438
+ // src/cli/notify.ts
439
+ import { existsSync as existsSync5, readFileSync as readFileSync6 } from "node:fs";
440
+
441
+ // 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");
445
+ function storageRoot(appId) {
446
+ const base = (process.env.QQ_DATA_DIR ?? "").trim() || LEGACY_ROOT;
447
+ return appId ? join4(base, "roles", appId) : base;
448
+ }
449
+ function storageFile(name, appId) {
450
+ return join4(storageRoot(appId), name);
451
+ }
452
+
453
+ // src/core/outbox.ts
454
+ 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
464
+ } from "node:fs";
465
+ import { dirname as dirname3 } from "node:path";
466
+ import { randomUUID } from "node:crypto";
467
+ var OUTBOX_SENT_RETENTION_MS = 24 * 60 * 60 * 1000;
468
+ var OUTBOX_SENT_RETENTION_LIMIT = 20;
469
+ var OUTBOX_DEFAULT_RETRY_BASE_MS = 1000;
470
+ var OUTBOX_DEFAULT_RETRY_MAX_MS = 60000;
471
+ var DEFAULT_POLL_INTERVAL_MS = 1000;
472
+ var DEFAULT_LEASE_MS = 30000;
473
+ var DEFAULT_LOCK_WAIT_MS = 5000;
474
+ var DEFAULT_LOCK_STALE_MS = 30000;
475
+ var sleepArray = new Int32Array(new SharedArrayBuffer(4));
476
+ function nonNegative(value, fallback, name) {
477
+ const resolved = value ?? fallback;
478
+ if (!Number.isFinite(resolved) || resolved < 0)
479
+ throw new Error(`${name} 必须是 >= 0 的有限数`);
480
+ return resolved;
481
+ }
482
+ function positive(value, fallback, name) {
483
+ const resolved = nonNegative(value, fallback, name);
484
+ if (resolved === 0)
485
+ throw new Error(`${name} 必须 > 0`);
486
+ return resolved;
487
+ }
488
+ function errorText(error) {
489
+ return error instanceof Error ? error.message : String(error);
490
+ }
491
+ function jsonSnapshot(value, label) {
492
+ const encoded = JSON.stringify(value);
493
+ if (encoded === undefined)
494
+ throw new Error(`Outbox ${label} 必须是可 JSON 序列化的值`);
495
+ return JSON.parse(encoded);
496
+ }
497
+ function delay(ms) {
498
+ return new Promise((resolve) => setTimeout(resolve, ms));
499
+ }
500
+ function atomicWrite(filePath, document) {
501
+ mkdirSync(dirname3(filePath), { recursive: true });
502
+ const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
503
+ try {
504
+ writeFileSync2(temporary, JSON.stringify(document, null, 2), { mode: 384 });
505
+ renameSync(temporary, filePath);
506
+ } catch (error) {
507
+ try {
508
+ unlinkSync2(temporary);
509
+ } catch {}
510
+ throw error;
511
+ }
512
+ }
513
+ function readDocument(filePath, now) {
514
+ if (!existsSync3(filePath))
515
+ return { version: 1, entries: [] };
516
+ const raw = JSON.parse(readFileSync4(filePath, "utf8"));
517
+ if (Array.isArray(raw)) {
518
+ return { version: 1, entries: pruneOutboxEntries(raw, now) };
519
+ }
520
+ if (typeof raw !== "object" || raw === null || raw.version !== 1 || !Array.isArray(raw.entries)) {
521
+ throw new Error(`Outbox 文件格式无效: ${filePath}`);
522
+ }
523
+ const entries = raw.entries;
524
+ return { version: 1, entries: pruneOutboxEntries(entries, now) };
525
+ }
526
+ function pruneOutboxEntries(entries, now = Date.now()) {
527
+ const indexed = entries.map((entry, index) => ({ entry, index }));
528
+ 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));
529
+ 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);
530
+ }
531
+ function createOutbox(options = {}) {
532
+ const filePath = options.filePath ?? process.env.QQ_OUTBOX_FILE ?? storageFile("outbox.json");
533
+ const pollIntervalMs = nonNegative(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, "pollIntervalMs");
534
+ const retryBaseMs = nonNegative(options.retryBaseMs, OUTBOX_DEFAULT_RETRY_BASE_MS, "retryBaseMs");
535
+ const retryMaxMs = nonNegative(options.retryMaxMs, OUTBOX_DEFAULT_RETRY_MAX_MS, "retryMaxMs");
536
+ const leaseMs = positive(options.leaseMs, DEFAULT_LEASE_MS, "leaseMs");
537
+ const lockWaitMs = positive(options.lockWaitMs, DEFAULT_LOCK_WAIT_MS, "lockWaitMs");
538
+ const lockStaleMs = positive(options.lockStaleMs, DEFAULT_LOCK_STALE_MS, "lockStaleMs");
539
+ const owner = `${process.pid}:${randomUUID()}`;
540
+ const handlers = new Map;
541
+ const inFlight = new Map;
542
+ const automatic = new Set;
543
+ let timer;
544
+ let stopped = false;
545
+ let flushing;
546
+ function withLock(fn) {
547
+ mkdirSync(dirname3(filePath), { recursive: true });
548
+ const lockPath = `${filePath}.lock`;
549
+ const token = `${owner}:${Date.now()}:${randomUUID()}`;
550
+ const deadline = Date.now() + lockWaitMs;
551
+ for (;; ) {
552
+ try {
553
+ const fd = openSync(lockPath, "wx", 384);
554
+ try {
555
+ writeFileSync2(fd, token);
556
+ } finally {
557
+ closeSync(fd);
558
+ }
559
+ break;
560
+ } catch (error) {
561
+ try {
562
+ if (Date.now() - statSync3(lockPath).mtimeMs > lockStaleMs)
563
+ unlinkSync2(lockPath);
564
+ } catch {}
565
+ if (Date.now() >= deadline)
566
+ throw new Error(`Outbox 锁等待超时: ${errorText(error)}`);
567
+ Atomics.wait(sleepArray, 0, 0, 10);
568
+ }
569
+ }
570
+ try {
571
+ return fn();
572
+ } finally {
573
+ try {
574
+ if (readFileSync4(lockPath, "utf8") === token)
575
+ unlinkSync2(lockPath);
576
+ } catch {}
577
+ }
578
+ }
579
+ function mutate(fn) {
580
+ return withLock(() => {
581
+ const document = readDocument(filePath, Date.now());
582
+ const result = fn(document.entries);
583
+ document.entries = pruneOutboxEntries(document.entries);
584
+ atomicWrite(filePath, document);
585
+ return result;
586
+ });
587
+ }
588
+ function clone(entry) {
589
+ return JSON.parse(JSON.stringify(entry));
590
+ }
591
+ function clearLease(entry) {
592
+ delete entry.leaseOwner;
593
+ delete entry.leaseUntil;
594
+ }
595
+ function transitionRecovered(entry, now, maxAttempts) {
596
+ if (entry.state !== "sending")
597
+ return false;
598
+ const exhausted = maxAttempts !== undefined && entry.attempts >= maxAttempts;
599
+ entry.state = exhausted ? "failed" : "pending";
600
+ entry.updatedAt = now;
601
+ entry.nextAttemptAt = now;
602
+ entry.lastError = exhausted ? `${entry.lastError ? `${entry.lastError}; ` : ""}崩溃恢复后已达到 maxAttempts=${maxAttempts}` : "进程在 sending 期间退出,发送结果未知;按至少一次语义恢复";
603
+ clearLease(entry);
604
+ return true;
605
+ }
606
+ async function recover(recoverOptions = {}) {
607
+ const now = Date.now();
608
+ return mutate((entries) => {
609
+ const recovered = [];
610
+ const exhausted = [];
611
+ for (const entry of entries) {
612
+ if (entry.state !== "sending")
613
+ continue;
614
+ if (inFlight.has(entry.id) && entry.leaseOwner?.startsWith(`${owner}:`))
615
+ continue;
616
+ const expired = entry.leaseUntil === undefined || entry.leaseUntil <= now;
617
+ if (!recoverOptions.ignoreLeases && !expired)
618
+ continue;
619
+ transitionRecovered(entry, now, recoverOptions.maxAttempts);
620
+ const snapshot = clone(entry);
621
+ if (snapshot.state === "failed")
622
+ exhausted.push(snapshot);
623
+ else
624
+ recovered.push(snapshot);
625
+ }
626
+ return { recovered, exhausted };
627
+ });
628
+ }
629
+ async function dispatchInternal(id, dispatchOptions) {
630
+ const handlerlessSnapshot = readDocument(filePath, Date.now()).entries.find((entry) => entry.id === id);
631
+ if (!handlerlessSnapshot)
632
+ return null;
633
+ const handler = handlers.get(handlerlessSnapshot.kind);
634
+ if (!handler)
635
+ return clone(handlerlessSnapshot);
636
+ const now = Date.now();
637
+ const token = `${owner}:${randomUUID()}`;
638
+ const claimed = withLock(() => {
639
+ const document = readDocument(filePath, now);
640
+ const entry = document.entries.find((candidate) => candidate.id === id);
641
+ if (!entry)
642
+ return { entry: null };
643
+ if (entry.state === "sent")
644
+ return { entry: clone(entry) };
645
+ if (entry.state === "sending" && entry.leaseUntil !== undefined && entry.leaseUntil > now) {
646
+ return { entry: null };
647
+ }
648
+ if ((entry.state === "pending" || entry.state === "failed" || entry.state === "sending") && !dispatchOptions.force && entry.nextAttemptAt > now) {
649
+ return { entry: clone(entry) };
650
+ }
651
+ const maxAttempts = dispatchOptions.maxAttempts;
652
+ if (maxAttempts !== undefined && entry.attempts >= maxAttempts) {
653
+ if (entry.state !== "failed") {
654
+ entry.state = "failed";
655
+ entry.updatedAt = now;
656
+ clearLease(entry);
657
+ atomicWrite(filePath, document);
658
+ }
659
+ return { entry: clone(entry) };
660
+ }
661
+ entry.state = "sending";
662
+ entry.attempts += 1;
663
+ entry.updatedAt = now;
664
+ entry.leaseOwner = token;
665
+ entry.leaseUntil = now + leaseMs;
666
+ delete entry.lastError;
667
+ atomicWrite(filePath, document);
668
+ return { entry: clone(entry), token };
669
+ });
670
+ if (!claimed.entry || !("token" in claimed))
671
+ return claimed.entry;
672
+ try {
673
+ const receipt = await handler(clone(claimed.entry));
674
+ const persistedReceipt = receipt === undefined ? null : jsonSnapshot(receipt, "receipt");
675
+ return mutate((entries) => {
676
+ const current = entries.find((entry) => entry.id === id);
677
+ if (!current || current.leaseOwner !== token)
678
+ return current ? clone(current) : null;
679
+ const completedAt = Date.now();
680
+ current.state = "sent";
681
+ current.updatedAt = completedAt;
682
+ current.receipt = persistedReceipt;
683
+ delete current.lastError;
684
+ clearLease(current);
685
+ return clone(current);
686
+ });
687
+ } catch (error) {
688
+ const failed = mutate((entries) => {
689
+ const current = entries.find((entry) => entry.id === id);
690
+ if (!current || current.leaseOwner !== token)
691
+ return current ? clone(current) : null;
692
+ const failedAt = Date.now();
693
+ current.state = "failed";
694
+ current.updatedAt = failedAt;
695
+ current.lastError = errorText(error);
696
+ current.nextAttemptAt = failedAt + Math.min(retryMaxMs, retryBaseMs * 2 ** Math.max(0, current.attempts - 1));
697
+ clearLease(current);
698
+ return clone(current);
699
+ });
700
+ if (automatic.has(id))
701
+ return failed;
702
+ throw error;
703
+ }
704
+ }
705
+ function dispatch(id, dispatchOptions = {}) {
706
+ const existing = inFlight.get(id);
707
+ if (existing)
708
+ return existing;
709
+ const promise = dispatchInternal(id, dispatchOptions).finally(() => {
710
+ if (inFlight.get(id) === promise)
711
+ inFlight.delete(id);
712
+ });
713
+ inFlight.set(id, promise);
714
+ return promise;
715
+ }
716
+ async function flush(flushOptions = {}) {
717
+ if (flushing)
718
+ return flushing;
719
+ const run = (async () => {
720
+ const results = new Map;
721
+ for (;; ) {
722
+ await recover({ maxAttempts: flushOptions.maxAttempts });
723
+ const entries = readDocument(filePath, Date.now()).entries;
724
+ const candidates = entries.filter((entry) => {
725
+ if (entry.state !== "pending" && entry.state !== "failed")
726
+ return false;
727
+ if (!handlers.has(entry.kind))
728
+ return false;
729
+ if (flushOptions.maxAttempts !== undefined && entry.attempts >= flushOptions.maxAttempts)
730
+ return false;
731
+ return flushOptions.force || flushOptions.wait || entry.nextAttemptAt <= Date.now();
732
+ });
733
+ const settled = await Promise.all(candidates.map(async (entry) => {
734
+ const result = await dispatch(entry.id, flushOptions);
735
+ if (result)
736
+ results.set(entry.id, result);
737
+ return result;
738
+ }));
739
+ if (!flushOptions.wait)
740
+ break;
741
+ const after = readDocument(filePath, Date.now()).entries;
742
+ const active = after.filter((entry) => (entry.state === "pending" || entry.state === "failed") && handlers.has(entry.kind) && (flushOptions.maxAttempts === undefined || entry.attempts < flushOptions.maxAttempts));
743
+ const waitingLocal = after.some((entry) => entry.state === "sending" && inFlight.has(entry.id));
744
+ if (active.length === 0 && !waitingLocal)
745
+ break;
746
+ if (settled.length === 0 && !waitingLocal) {
747
+ const next = active.reduce((minimum, entry) => Math.min(minimum, entry.nextAttemptAt), Number.POSITIVE_INFINITY);
748
+ if (Number.isFinite(next))
749
+ await delay(Math.max(1, next - Date.now()));
750
+ else
751
+ break;
752
+ } else {
753
+ await delay(1);
754
+ }
755
+ }
756
+ return [...results.values()];
757
+ })();
758
+ flushing = run;
759
+ try {
760
+ return await run;
761
+ } finally {
762
+ if (flushing === run)
763
+ flushing = undefined;
764
+ }
765
+ }
766
+ async function drain() {
767
+ while (inFlight.size > 0) {
768
+ const pending = [...inFlight.values()];
769
+ const outcomes = await Promise.allSettled(pending);
770
+ const rejection = outcomes.find((outcome) => outcome.status === "rejected");
771
+ if (rejection)
772
+ throw rejection.reason;
773
+ }
774
+ }
775
+ return {
776
+ filePath,
777
+ register(kind, handler) {
778
+ if (!kind)
779
+ throw new Error("Outbox kind 不能为空");
780
+ handlers.set(kind, handler);
781
+ return () => {
782
+ if (handlers.get(kind) === handler)
783
+ handlers.delete(kind);
784
+ };
785
+ },
786
+ async enqueue(input) {
787
+ if (!input.kind)
788
+ throw new Error("Outbox kind 不能为空");
789
+ if (input.payload === undefined)
790
+ throw new Error("Outbox payload 必须是 JSON 值,不能为 undefined");
791
+ if (input.nextAttemptAt !== undefined && !Number.isFinite(input.nextAttemptAt)) {
792
+ throw new Error("Outbox nextAttemptAt 必须是有限时间戳");
793
+ }
794
+ const persistedCtx = jsonSnapshot(input.ctx, "ctx");
795
+ const persistedPayload = jsonSnapshot(input.payload, "payload");
796
+ const now = Date.now();
797
+ const id = input.id ?? randomUUID();
798
+ const entry = mutate((entries) => {
799
+ const existing = entries.find((candidate) => candidate.id === id);
800
+ if (existing)
801
+ return clone(existing);
802
+ const created = {
803
+ id,
804
+ kind: input.kind,
805
+ ctx: persistedCtx,
806
+ payload: persistedPayload,
807
+ ...input.sessionId !== undefined ? { sessionId: input.sessionId } : {},
808
+ ...input.turnId !== undefined ? { turnId: input.turnId } : {},
809
+ state: "pending",
810
+ attempts: 0,
811
+ createdAt: now,
812
+ updatedAt: now,
813
+ nextAttemptAt: input.nextAttemptAt ?? now
814
+ };
815
+ entries.push(created);
816
+ return clone(created);
817
+ });
818
+ automatic.add(id);
819
+ dispatch(id).finally(() => automatic.delete(id)).catch(() => {});
820
+ return entry;
821
+ },
822
+ dispatch,
823
+ recover,
824
+ flush,
825
+ async start(startOptions = {}) {
826
+ stopped = false;
827
+ if (startOptions.recover !== false)
828
+ await recover({ maxAttempts: startOptions.maxAttempts });
829
+ if (pollIntervalMs === 0 || timer)
830
+ return;
831
+ timer = setInterval(() => {
832
+ if (stopped)
833
+ return;
834
+ flush({ maxAttempts: startOptions.maxAttempts }).catch(() => {});
835
+ }, pollIntervalMs);
836
+ timer.unref?.();
837
+ flush({ maxAttempts: startOptions.maxAttempts }).catch(() => {});
838
+ },
839
+ stop() {
840
+ stopped = true;
841
+ if (timer)
842
+ clearInterval(timer);
843
+ timer = undefined;
844
+ },
845
+ drain,
846
+ async list() {
847
+ return readDocument(filePath, Date.now()).entries.map((entry) => clone(entry));
848
+ },
849
+ async get(id) {
850
+ const entry = readDocument(filePath, Date.now()).entries.find((candidate) => candidate.id === id);
851
+ return entry ? clone(entry) : undefined;
852
+ }
853
+ };
854
+ }
855
+
856
+ // 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");
862
+ function loadEnvFile(path) {
863
+ const content = readFileSync5(path, "utf-8");
864
+ for (const line of content.split(`
865
+ `)) {
866
+ const trimmed = line.trim();
867
+ if (!trimmed || trimmed.startsWith("#"))
868
+ continue;
869
+ const eqIdx = trimmed.indexOf("=");
870
+ if (eqIdx < 0)
871
+ continue;
872
+ const key = trimmed.slice(0, eqIdx).trim();
873
+ const val = trimmed.slice(eqIdx + 1).trim();
874
+ if (!process.env[key]) {
875
+ process.env[key] = val;
876
+ }
877
+ }
878
+ }
879
+
880
+ // src/core/notify-sink.ts
881
+ function resolveNotifyRecipients(configured, explicit) {
882
+ const users = [...configured];
883
+ if (explicit)
884
+ return users.includes(explicit) ? explicit : "";
885
+ return users.length === 1 ? users[0] : "";
886
+ }
887
+ function defaultOutboxPath() {
888
+ return storageFile("outbox.json");
889
+ }
890
+
891
+ // src/cli/notify.ts
892
+ var NOTIFY_DEFAULT_MAX_CHARS = 1500;
893
+ function parseArgs(argv) {
894
+ const parsed = { maxChars: NOTIFY_DEFAULT_MAX_CHARS, dryRun: false, json: false, help: false };
895
+ for (let i = 0;i < argv.length; i++) {
896
+ const a = argv[i];
897
+ const next = argv[i + 1];
898
+ switch (a) {
899
+ case "--text":
900
+ parsed.text = next;
901
+ i++;
902
+ break;
903
+ case "--file":
904
+ parsed.filePath = next;
905
+ i++;
906
+ break;
907
+ case "--stdin":
908
+ parsed.stdin = true;
909
+ break;
910
+ case "--user":
911
+ parsed.user = next;
912
+ i++;
913
+ break;
914
+ case "--id":
915
+ parsed.id = next;
916
+ i++;
917
+ break;
918
+ case "--max-chars":
919
+ parsed.maxChars = Number(next);
920
+ i++;
921
+ break;
922
+ case "--ttl-hours":
923
+ parsed.ttlHours = Number(next);
924
+ i++;
925
+ break;
926
+ case "--dry-run":
927
+ parsed.dryRun = true;
928
+ break;
929
+ case "--json":
930
+ parsed.json = true;
931
+ break;
932
+ case "--help":
933
+ case "-h":
934
+ parsed.help = true;
935
+ i++;
936
+ break;
937
+ default:
938
+ throw new Error(`未知参数:${a}(用法:openqq notify --text "…" | --file <p> | --stdin)`);
939
+ }
940
+ }
941
+ if (!parsed.help && !parsed.text && !parsed.filePath && !parsed.stdin) {
942
+ throw new Error("必须提供正文来源:--text / --file / --stdin 三选一");
943
+ }
944
+ if (!Number.isFinite(parsed.maxChars) || parsed.maxChars < 0) {
945
+ throw new Error("--max-chars 必须是 >= 0 的有限数(0=不截断)");
946
+ }
947
+ return parsed;
948
+ }
949
+ function resolveUser(envAllowed, explicit) {
950
+ return resolveNotifyRecipients(envAllowed, explicit);
951
+ }
952
+ function readBody(parsed) {
953
+ if (parsed.text !== undefined)
954
+ return parsed.text;
955
+ if (parsed.filePath !== undefined) {
956
+ if (parsed.filePath === "-")
957
+ return readFileSync6(0, "utf8");
958
+ if (!existsSync5(parsed.filePath))
959
+ throw new Error(`--file 不存在:${parsed.filePath}`);
960
+ return readFileSync6(parsed.filePath, "utf8");
961
+ }
962
+ if (parsed.stdin)
963
+ return readFileSync6(0, "utf8");
964
+ return "";
965
+ }
966
+ async function runNotifyCli(argv, options = {}) {
967
+ const now = options.now ?? Date.now();
968
+ const parsed = parseArgs(argv);
969
+ if (parsed.help) {
970
+ const help = [
971
+ '用法:openqq notify --text "…" | --file <路径> | --stdin',
972
+ " --user <openid> 收件人;缺省取 ALLOWED_USERS 唯一项(多用户必须显式指定)",
973
+ " --id <key> 幂等键(同 key 不重复投递)",
974
+ " --max-chars <n> 截断上限,默认 1500,0 不截断",
975
+ " --ttl-hours <n> 队列等待上限,默认 24(env QQ_NOTIFY_TTL_HOURS 兜底)",
976
+ " --dry-run / --json 不入队 / 机器可读输出"
977
+ ].join(`
978
+ `);
979
+ console.log(help);
980
+ return { ok: true, queued: false, id: "", user: "", chars: 0, truncated: false, dryRun: true, json: parsed.json, reason: "help" };
981
+ }
982
+ if (!options.env && existsSync5(ENV_FILE))
983
+ loadEnvFile(ENV_FILE);
984
+ const allowedUsers = options.env ? [...options.env.allowedUsers] : String(process.env.ALLOWED_USERS ?? "").split(/[,\s]+/).filter(Boolean);
985
+ const user = resolveUser(allowedUsers, parsed.user);
986
+ if (!user) {
987
+ throw new Error(allowedUsers.length === 0 ? "ALLOWED_USERS 为空——fail-closed 不允许无名单入队(先在 ~/.openqq/.env 配置)" : parsed.user ? `收件人不在名单:${parsed.user}(ALLOWED_USERS 共 ${allowedUsers.length} 项,--user 必须精确命中;请核对 openid)` : "多用户名单必须用 --user <openid> 显式指定收件人");
988
+ }
989
+ const raw = readBody(parsed);
990
+ const max = parsed.maxChars;
991
+ const content = max === 0 ? raw : raw.length > max ? `${raw.slice(0, max)}…` : raw;
992
+ const id = parsed.id || `notify-${now.toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
993
+ const filePath = options.filePath ?? defaultOutboxPath();
994
+ if (parsed.dryRun) {
995
+ return { ok: true, queued: false, id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: true, json: parsed.json };
996
+ }
997
+ const ttlHours = parsed.ttlHours ?? Number(process.env.QQ_NOTIFY_TTL_HOURS ?? 24);
998
+ const nextAttemptAt = parsed.ttlHours !== undefined && Number.isFinite(ttlHours) && ttlHours > 0 ? now + ttlHours * 60 * 60 * 1000 : now;
999
+ const outbox = createOutbox({ filePath, pollIntervalMs: 0 });
1000
+ const entry = await outbox.enqueue({
1001
+ ...parsed.id ? { id: parsed.id } : {},
1002
+ kind: "notify",
1003
+ payload: { text: content },
1004
+ ctx: { type: "c2c", userId: user, msgId: "", content: "(openqq notify)", timestamp: String(now) },
1005
+ sessionId: "",
1006
+ nextAttemptAt
1007
+ });
1008
+ return { ok: true, queued: true, id: entry.id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: false, json: parsed.json };
1009
+ }
1010
+
1011
+ // src/cli/watchdog-main.ts
1012
+ import { join as join6 } from "path";
1013
+ import { homedir as homedir6 } from "os";
1014
+ var DEFAULT_INTERVAL_MIN = 10;
1015
+ function parseArgs2(argv) {
1016
+ const loop = argv.includes("--loop");
1017
+ const idx = argv.indexOf("--interval-min");
1018
+ const raw = idx >= 0 ? Number(argv[idx + 1]) : Number.NaN;
1019
+ const intervalMin = Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_INTERVAL_MIN;
1020
+ return { loop, intervalMin };
1021
+ }
1022
+ function currentAppId() {
1023
+ return readAppId() ?? readEnvField(join6(homedir6(), ".openqq", ".env"), "QQ_APP_ID");
1024
+ }
1025
+ function alert(message) {
1026
+ 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
+ }
1028
+ async function tick(appId) {
1029
+ const result = await superviseOnce({
1030
+ paths: botWatchdogPaths(appId),
1031
+ spawn: () => startBot(import.meta.url, (line) => console.log(line)),
1032
+ log: (line) => console.log(line),
1033
+ alert
1034
+ });
1035
+ console.log(`[supervisor] ${result.action}:${result.detail}`);
1036
+ if (result.action !== "ok")
1037
+ appendWatchdogLog(`[supervisor] ${result.action}:${result.detail}`);
1038
+ }
1039
+ async function main() {
1040
+ const args = parseArgs2(process.argv.slice(2));
1041
+ const appId = currentAppId();
1042
+ if (!appId) {
1043
+ console.error("[watchdog] 未找到 QQ_APP_ID(~/.openqq/.env),无法定位实例锁");
1044
+ process.exit(1);
1045
+ }
1046
+ console.log(`[watchdog] 模式=${args.loop ? `loop/${args.intervalMin}min` : "once"}(监督矩阵:冷却2m/强度3次15m/优雅杀8s)`);
1047
+ await tick(appId);
1048
+ if (!args.loop)
1049
+ return;
1050
+ const timer = setInterval(() => {
1051
+ tick(appId).catch((error) => console.error("[watchdog] 巡检失败:", error instanceof Error ? error.message : error));
1052
+ }, args.intervalMin * 60000);
1053
+ const stop = () => {
1054
+ clearInterval(timer);
1055
+ process.exit(0);
1056
+ };
1057
+ process.once("SIGINT", stop);
1058
+ process.once("SIGTERM", stop);
1059
+ }
1060
+ main().catch((error) => {
1061
+ console.error("[watchdog] 致命错误:", error instanceof Error ? error.message : error);
1062
+ process.exit(1);
1063
+ });