@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.
- package/README.md +303 -229
- package/README.zh-CN.md +313 -0
- package/bin/openqq.js +13 -0
- package/dist/notify-cli.js +92 -26
- package/dist/opencode-qqbot-plugin.js +1201 -67
- package/dist/openqq-bot.js +3963 -893
- package/dist/openqq-cli.js +980 -0
- package/dist/openqq-watchdog.js +1326 -0
- package/package.json +8 -5
- package/src/bridge.ts +1599 -150
- package/src/cli/notify.ts +170 -158
- package/src/cli/openqq-main.ts +95 -0
- package/src/cli/service-main.ts +302 -0
- package/src/cli/watchdog-main.ts +92 -0
- package/src/commands.ts +670 -554
- package/src/config.ts +122 -3
- package/src/core/bot-config.ts +66 -0
- package/src/core/bot-control.ts +166 -0
- package/src/core/bot-launcher.ts +110 -15
- package/src/core/card-approval.ts +20 -9
- package/src/core/cron-reminders.ts +84 -0
- package/src/core/delivery.ts +145 -54
- package/src/core/discovery.ts +207 -151
- package/src/core/error-rescue.ts +1 -1
- package/src/core/file-log.ts +50 -9
- package/src/core/form-bridge.ts +14 -5
- package/src/core/form-journal.ts +4 -4
- package/src/core/gateway-state.ts +3 -3
- package/src/core/inflight-journal.ts +215 -36
- package/src/core/instance-lock.ts +42 -3
- package/src/core/linkwatch.ts +3 -4
- package/src/core/log-rotate.ts +91 -0
- package/src/core/markdown.ts +117 -0
- package/src/core/message-queue.ts +242 -91
- package/src/core/mirror.ts +228 -182
- package/src/core/notices.ts +62 -0
- package/src/core/notify-sink.ts +93 -96
- package/src/core/outbound-sanitize.ts +29 -0
- package/src/core/outbox.ts +10 -9
- package/src/core/permission.ts +634 -303
- package/src/core/question-form.ts +230 -0
- package/src/core/queue-view.ts +662 -0
- package/src/core/send-media.ts +61 -2
- package/src/core/start-error.ts +26 -0
- package/src/core/storage.ts +34 -0
- package/src/core/stt.ts +55 -0
- package/src/core/supervisor-election.ts +53 -0
- package/src/core/watchdog.ts +670 -0
- package/src/core/zombie-reaper.ts +127 -0
- package/src/index.ts +262 -162
- package/src/opencode/client.ts +237 -27
- package/src/opencode/eventstream.ts +94 -12
- package/src/opencode/history.ts +4 -2
- package/src/opencode/mirror.ts +25 -5
- package/src/opencode/sessions.ts +135 -37
- package/src/plugin-entry.ts +139 -115
- package/src/qq/api.ts +165 -61
- package/src/qq/gateway.ts +114 -16
- package/src/qq/media.ts +21 -0
- package/src/qq/sender.ts +79 -18
- package/src/qq/types.ts +7 -0
|
@@ -1,34 +1,417 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
// src/plugin-entry.ts
|
|
3
3
|
import { Plugin } from "@opencode/plugin";
|
|
4
|
-
import { join as
|
|
5
|
-
import { homedir as
|
|
6
|
-
import { appendFileSync, existsSync as
|
|
7
|
-
import { fileURLToPath } from "url";
|
|
4
|
+
import { join as join9 } from "path";
|
|
5
|
+
import { homedir as homedir7 } from "os";
|
|
6
|
+
import { appendFileSync, existsSync as existsSync9, renameSync as renameSync3, statSync as statSync6 } from "fs";
|
|
7
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
8
8
|
|
|
9
|
-
// src/core/
|
|
10
|
-
import {
|
|
11
|
-
import { join } from "path";
|
|
9
|
+
// src/core/watchdog.ts
|
|
10
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2, statSync as statSync3, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
11
|
+
import { dirname, join as join2 } from "path";
|
|
12
12
|
import { homedir } from "os";
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
13
|
+
|
|
14
|
+
// src/core/log-rotate.ts
|
|
15
|
+
import { existsSync, renameSync, rmSync, statSync } from "fs";
|
|
16
|
+
var MB = 1024 * 1024;
|
|
17
|
+
var num = (v, d) => {
|
|
18
|
+
const n = Number(v);
|
|
19
|
+
return Number.isFinite(n) && n > 0 ? n : d;
|
|
20
|
+
};
|
|
21
|
+
function logLimitsFromEnv(env = process.env) {
|
|
22
|
+
return {
|
|
23
|
+
maxBytes: num(env.QQ_LOG_MAX_MB, 20) * MB,
|
|
24
|
+
keepBackups: Math.floor(num(env.QQ_LOG_KEEP, 4)),
|
|
25
|
+
totalBudgetBytes: num(env.QQ_LOG_TOTAL_MB, 100) * MB
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
function rotateLogIfNeeded(logPath, limits = logLimitsFromEnv()) {
|
|
29
|
+
try {
|
|
30
|
+
if (!existsSync(logPath) || statSync(logPath).size <= limits.maxBytes)
|
|
31
|
+
return false;
|
|
32
|
+
try {
|
|
33
|
+
rmSync(`${logPath}.${limits.keepBackups}`, { force: true });
|
|
34
|
+
} catch {}
|
|
35
|
+
for (let i = limits.keepBackups - 1;i >= 1; i--) {
|
|
36
|
+
const from = `${logPath}.${i}`;
|
|
37
|
+
if (!existsSync(from))
|
|
38
|
+
continue;
|
|
39
|
+
try {
|
|
40
|
+
renameSync(from, `${logPath}.${i + 1}`);
|
|
41
|
+
} catch {}
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
renameSync(logPath, `${logPath}.1`);
|
|
45
|
+
} catch {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
return true;
|
|
49
|
+
} catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
16
52
|
}
|
|
17
|
-
function
|
|
18
|
-
|
|
53
|
+
function enforceLogBudget(logPath, limits = logLimitsFromEnv()) {
|
|
54
|
+
try {
|
|
55
|
+
const sizes = new Map;
|
|
56
|
+
let total = 0;
|
|
57
|
+
for (let i = 0;i <= 64; i++) {
|
|
58
|
+
const p = i === 0 ? logPath : `${logPath}.${i}`;
|
|
59
|
+
if (!existsSync(p))
|
|
60
|
+
break;
|
|
61
|
+
const s = statSync(p).size;
|
|
62
|
+
sizes.set(i, s);
|
|
63
|
+
total += s;
|
|
64
|
+
}
|
|
65
|
+
for (let i = limits.keepBackups;i >= 1 && total > limits.totalBudgetBytes; i--) {
|
|
66
|
+
const s = sizes.get(i);
|
|
67
|
+
if (s === undefined)
|
|
68
|
+
continue;
|
|
69
|
+
try {
|
|
70
|
+
rmSync(`${logPath}.${i}`, { force: true });
|
|
71
|
+
total -= s;
|
|
72
|
+
} catch {}
|
|
73
|
+
}
|
|
74
|
+
} catch {}
|
|
19
75
|
}
|
|
20
|
-
|
|
76
|
+
|
|
77
|
+
// src/core/instance-lock.ts
|
|
78
|
+
import { openSync, readFileSync, readdirSync, writeFileSync, closeSync, unlinkSync, statSync as statSync2, utimesSync, mkdirSync } from "fs";
|
|
79
|
+
import { join } from "path";
|
|
80
|
+
function releaseLocksOfPid(pid, dir) {
|
|
81
|
+
let names;
|
|
21
82
|
try {
|
|
22
|
-
|
|
83
|
+
names = readdirSync(dir);
|
|
23
84
|
} catch {
|
|
85
|
+
return [];
|
|
86
|
+
}
|
|
87
|
+
const cleared = [];
|
|
88
|
+
for (const name of names) {
|
|
89
|
+
if (!/^openqq-.+\.lock$/.test(name))
|
|
90
|
+
continue;
|
|
91
|
+
const p = join(dir, name);
|
|
92
|
+
try {
|
|
93
|
+
const holder = JSON.parse(readFileSync(p, "utf-8"));
|
|
94
|
+
if (holder.pid === pid) {
|
|
95
|
+
unlinkSync(p);
|
|
96
|
+
cleared.push(p);
|
|
97
|
+
}
|
|
98
|
+
} catch {}
|
|
99
|
+
}
|
|
100
|
+
return cleared;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// src/core/watchdog.ts
|
|
104
|
+
var HEARTBEAT_STALE_MS = 5 * 60000;
|
|
105
|
+
function botWatchdogPaths(appId) {
|
|
106
|
+
const dir = join2(homedir(), ".openqq");
|
|
107
|
+
return { lockPath: join2(dir, `openqq-${appId}.lock`), heartbeatPath: join2(dir, "heartbeat") };
|
|
108
|
+
}
|
|
109
|
+
function isPidAlive(pid) {
|
|
110
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
24
111
|
return false;
|
|
112
|
+
try {
|
|
113
|
+
process.kill(pid, 0);
|
|
114
|
+
return true;
|
|
115
|
+
} catch (error) {
|
|
116
|
+
return error.code === "EPERM";
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
function ageOf(path, now) {
|
|
120
|
+
try {
|
|
121
|
+
return Math.max(0, now - statSync3(path).mtimeMs);
|
|
122
|
+
} catch {
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
function readBotHealth(paths, now = Date.now()) {
|
|
127
|
+
const lockAgeMs = ageOf(paths.lockPath, now);
|
|
128
|
+
let lockPid = null;
|
|
129
|
+
if (lockAgeMs !== null) {
|
|
130
|
+
try {
|
|
131
|
+
const raw = JSON.parse(readFileSync2(paths.lockPath, "utf-8"));
|
|
132
|
+
if (typeof raw.pid === "number" && Number.isInteger(raw.pid))
|
|
133
|
+
lockPid = raw.pid;
|
|
134
|
+
} catch {}
|
|
135
|
+
}
|
|
136
|
+
return {
|
|
137
|
+
lockPid,
|
|
138
|
+
lockAgeMs,
|
|
139
|
+
pidAlive: lockPid === null ? null : isPidAlive(lockPid),
|
|
140
|
+
heartbeatAgeMs: ageOf(paths.heartbeatPath, now)
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function appendWatchdogLog(line) {
|
|
144
|
+
try {
|
|
145
|
+
const logPath = join2(homedir(), ".openqq", "openqq.log");
|
|
146
|
+
const limits = logLimitsFromEnv();
|
|
147
|
+
if (existsSync2(logPath) && statSync3(logPath).size > limits.maxBytes) {
|
|
148
|
+
if (rotateLogIfNeeded(logPath, limits))
|
|
149
|
+
enforceLogBudget(logPath, limits);
|
|
150
|
+
}
|
|
151
|
+
writeFileSync2(logPath, `${new Date().toISOString()} ${line}
|
|
152
|
+
`, { flag: "a" });
|
|
153
|
+
} catch {}
|
|
154
|
+
}
|
|
155
|
+
function appendKillLog(entry, logPath = join2(homedir(), ".openqq", "kills.log")) {
|
|
156
|
+
try {
|
|
157
|
+
writeFileSync2(logPath, `${JSON.stringify(entry)}
|
|
158
|
+
`, { flag: "a" });
|
|
159
|
+
const limits = logLimitsFromEnv();
|
|
160
|
+
if (existsSync2(logPath) && statSync3(logPath).size > limits.maxBytes) {
|
|
161
|
+
if (rotateLogIfNeeded(logPath, limits))
|
|
162
|
+
enforceLogBudget(logPath, limits);
|
|
163
|
+
}
|
|
164
|
+
} catch {}
|
|
165
|
+
}
|
|
166
|
+
var DEFAULT_SUPERVISOR_POLICY = {
|
|
167
|
+
cooldownMs: 2 * 60000,
|
|
168
|
+
maxRestarts: 3,
|
|
169
|
+
windowMs: 15 * 60000,
|
|
170
|
+
graceMs: 8000,
|
|
171
|
+
claimTtlMs: 90000
|
|
172
|
+
};
|
|
173
|
+
function decideSupervise(health, state, now, policy = DEFAULT_SUPERVISOR_POLICY) {
|
|
174
|
+
const staleHeartbeat = health.heartbeatAgeMs !== null && health.heartbeatAgeMs > HEARTBEAT_STALE_MS;
|
|
175
|
+
const needsRestart = health.lockPid === null || health.pidAlive === false || staleHeartbeat;
|
|
176
|
+
if (!needsRestart)
|
|
177
|
+
return { kind: "ok" };
|
|
178
|
+
const windowStart = now - policy.windowMs;
|
|
179
|
+
const recentRestarts = state.restartLog.filter((t) => t > windowStart).length;
|
|
180
|
+
if (recentRestarts >= policy.maxRestarts)
|
|
181
|
+
return { kind: "give-up", restarts: recentRestarts };
|
|
182
|
+
const last = state.restartLog[state.restartLog.length - 1] ?? null;
|
|
183
|
+
if (last !== null && now - last < policy.cooldownMs)
|
|
184
|
+
return { kind: "cooldown", untilMs: last + policy.cooldownMs };
|
|
185
|
+
if (health.lockPid !== null && health.pidAlive !== false && staleHeartbeat) {
|
|
186
|
+
return {
|
|
187
|
+
kind: "grace-kill-spawn",
|
|
188
|
+
killPid: health.lockPid,
|
|
189
|
+
reason: `\u5FC3\u8DF3\u9648\u65E7 ${Math.round((health.heartbeatAgeMs ?? 0) / 60000)} \u5206\u949F\uFF08\u8FDB\u7A0B\u6D3B\u4F46\u4E8B\u4EF6\u5FAA\u73AF\u65E0\u8FDB\u5C55\uFF09`
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
return { kind: "spawn", reason: health.lockPid === null ? "\u65E0\u5B9E\u4F8B\u9501\uFF08bot \u672A\u8FD0\u884C\uFF09" : "\u9501\u5B9A\u8FDB\u7A0B\u5DF2\u9000\u51FA" };
|
|
193
|
+
}
|
|
194
|
+
var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
195
|
+
var defaultSupervisorKill = (pid, signal) => {
|
|
196
|
+
try {
|
|
197
|
+
process.kill(pid, signal);
|
|
198
|
+
} catch {}
|
|
199
|
+
};
|
|
200
|
+
function readJson(path, fallback) {
|
|
201
|
+
try {
|
|
202
|
+
return { ...fallback, ...JSON.parse(readFileSync2(path, "utf-8")) };
|
|
203
|
+
} catch {
|
|
204
|
+
return fallback;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
async function superviseOnce(deps) {
|
|
208
|
+
const policy = deps.policy ?? DEFAULT_SUPERVISOR_POLICY;
|
|
209
|
+
const now = deps.now?.() ?? Date.now();
|
|
210
|
+
const log = deps.log ?? (() => {});
|
|
211
|
+
const sleep = deps.sleep ?? defaultSleep;
|
|
212
|
+
const kill = deps.kill ?? defaultSupervisorKill;
|
|
213
|
+
const isAlive = deps.isAlive ?? isPidAlive;
|
|
214
|
+
const statePath = deps.statePath ?? join2(homedir(), ".openqq", "supervisor.json");
|
|
215
|
+
const claimPath = deps.claimPath ?? join2(homedir(), ".openqq", "supervisor.lock");
|
|
216
|
+
const audit = (line) => {
|
|
217
|
+
if (deps.auditLogPath) {
|
|
218
|
+
try {
|
|
219
|
+
writeFileSync2(deps.auditLogPath, `${new Date().toISOString()} ${line}
|
|
220
|
+
`, { flag: "a" });
|
|
221
|
+
return;
|
|
222
|
+
} catch {}
|
|
223
|
+
}
|
|
224
|
+
appendWatchdogLog(line);
|
|
225
|
+
};
|
|
226
|
+
const claim = readJson(claimPath, { pid: 0, ts: 0 });
|
|
227
|
+
if (claim.ts && now - claim.ts < policy.claimTtlMs && claim.pid !== process.pid) {
|
|
228
|
+
return { action: "yield", detail: `\u76D1\u7763\u8005 pid=${claim.pid} \u6301\u9501\u4E2D`, killedPid: null, spawnedPid: null };
|
|
229
|
+
}
|
|
230
|
+
try {
|
|
231
|
+
writeFileSync2(claimPath, JSON.stringify({ pid: process.pid, ts: now }));
|
|
232
|
+
} catch {
|
|
233
|
+
return { action: "yield", detail: "\u8BA4\u9886\u9501\u4E0D\u53EF\u5199", killedPid: null, spawnedPid: null };
|
|
234
|
+
}
|
|
235
|
+
const release = () => {
|
|
236
|
+
try {
|
|
237
|
+
writeFileSync2(claimPath, JSON.stringify({ pid: 0, ts: 0 }));
|
|
238
|
+
} catch {}
|
|
239
|
+
};
|
|
240
|
+
try {
|
|
241
|
+
const health = readBotHealth(deps.paths, now);
|
|
242
|
+
const state = readJson(statePath, { restartLog: [] });
|
|
243
|
+
let action = decideSupervise(health, state, now, policy);
|
|
244
|
+
if (deps.request === "manual-restart" && action.kind === "ok") {
|
|
245
|
+
const windowStart = now - policy.windowMs;
|
|
246
|
+
const recentRestarts = state.restartLog.filter((t) => t > windowStart).length;
|
|
247
|
+
if (recentRestarts >= policy.maxRestarts) {
|
|
248
|
+
return {
|
|
249
|
+
action: "give-up",
|
|
250
|
+
detail: `15 \u5206\u949F\u5185\u5DF2\u91CD\u542F ${recentRestarts} \u6B21\uFF08\u76D1\u7763\u5F3A\u5EA6\u4E0A\u9650\uFF09\uFF0C\u4EBA\u5DE5\u91CD\u542F\u4EA6\u88AB\u62E6\u622A\uFF0C\u8BF7\u6392\u67E5\u6839\u56E0`,
|
|
251
|
+
killedPid: null,
|
|
252
|
+
spawnedPid: null
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
const last = state.restartLog[state.restartLog.length - 1] ?? null;
|
|
256
|
+
if (last !== null && now - last < policy.cooldownMs) {
|
|
257
|
+
return { action: "cooldown", detail: `\u8DDD\u4E0A\u6B21\u91CD\u542F\u4E0D\u8DB3 ${Math.round(policy.cooldownMs / 1000)}s\uFF08\u51B7\u5374\u671F\uFF09\uFF0C\u4EBA\u5DE5\u91CD\u542F\u8DF3\u8FC7`, killedPid: null, spawnedPid: null };
|
|
258
|
+
}
|
|
259
|
+
action = health.lockPid !== null && health.pidAlive !== false ? { kind: "grace-kill-spawn", killPid: health.lockPid, reason: "\u4EBA\u5DE5\u8BF7\u6C42\u91CD\u542F\uFF08openqq restart\uFF09" } : { kind: "spawn", reason: "\u4EBA\u5DE5\u8BF7\u6C42\u91CD\u542F\uFF08bot \u672A\u8FD0\u884C\uFF0C\u76F4\u63A5\u62C9\u8D77\uFF09" };
|
|
260
|
+
}
|
|
261
|
+
if (action.kind === "ok")
|
|
262
|
+
return { action: "ok", detail: "\u5065\u5EB7", killedPid: null, spawnedPid: null };
|
|
263
|
+
if (action.kind === "cooldown") {
|
|
264
|
+
log(`[supervisor] \u51B7\u5374\u4E2D\uFF08\u4E0A\u6B21\u91CD\u542F ${Math.round((now - (action.untilMs - policy.cooldownMs)) / 1000)}s \u524D\uFF09\uFF0C\u672C\u8F6E\u8DF3\u8FC7`);
|
|
265
|
+
return { action: "cooldown", detail: "\u51B7\u5374\u8DF3\u8FC7", killedPid: null, spawnedPid: null };
|
|
266
|
+
}
|
|
267
|
+
if (action.kind === "yield") {
|
|
268
|
+
return { action: "yield", detail: action.reason, killedPid: null, spawnedPid: null };
|
|
269
|
+
}
|
|
270
|
+
if (action.kind === "give-up") {
|
|
271
|
+
const message = `\u26A0\uFE0F QQBot \u770B\u95E8\u72D7\u5DF2\u8FBE\u91CD\u542F\u5F3A\u5EA6\u4E0A\u9650\uFF1A${action.restarts} \u6B21/${Math.round(policy.windowMs / 60000)} \u5206\u949F\u4ECD\u4E0D\u5065\u5EB7\uFF08\u540C\u56E0\u53CD\u590D\u6B7B\u4EA1\uFF09\u3002\u964D\u9891\u91CD\u8BD5\u7EE7\u7EED\u2014\u2014\u5DE1\u68C0\u4E0D\u4F1A\u505C\uFF0C\u5F3A\u5EA6\u7A97\u53E3\u6ED1\u52A8\u540E\u81EA\u52A8\u6062\u590D\uFF0C\u5F15\u64CE/\u73AF\u5883\u81EA\u6108\u5373\u81EA\u884C\u597D\u8F6C\uFF1B\u82E5\u6301\u7EED\u6536\u5230\u6B64\u544A\u8B66\uFF0C\u8BF7\u68C0\u67E5 ~/.openqq/openqq.log\uFF08bot \u4E0E\u770B\u95E8\u72D7\u7EDF\u4E00\u65E5\u5FD7\uFF09\u3002`;
|
|
272
|
+
audit(`give-up\uFF1A${message}`);
|
|
273
|
+
log(`[supervisor] give-up\uFF1A${action.restarts} \u6B21\u91CD\u542F\u4ECD\u5F02\u5E38\uFF0C\u964D\u9891\u91CD\u8BD5\u7EE7\u7EED\u5E76\u4E0A\u62A5\uFF08\u4E0D\u518D\u6C38\u52A8\u731B\u62C9\uFF09`);
|
|
274
|
+
const lastAlert = state.alertedAt ?? 0;
|
|
275
|
+
if (now - lastAlert > 30 * 60000) {
|
|
276
|
+
try {
|
|
277
|
+
deps.alert?.(message);
|
|
278
|
+
state.alertedAt = now;
|
|
279
|
+
writeFileSync2(statePath, JSON.stringify(state));
|
|
280
|
+
} catch {}
|
|
281
|
+
}
|
|
282
|
+
return { action: "give-up", detail: message, killedPid: null, spawnedPid: null };
|
|
283
|
+
}
|
|
284
|
+
let killedPid = null;
|
|
285
|
+
if (action.kind === "grace-kill-spawn" && action.killPid !== process.pid) {
|
|
286
|
+
const pid = action.killPid;
|
|
287
|
+
if (deps.request !== "manual-restart") {
|
|
288
|
+
await sleep(300);
|
|
289
|
+
const recheck = readBotHealth(deps.paths, Date.now());
|
|
290
|
+
const recheckFresh = recheck.heartbeatAgeMs !== null && recheck.heartbeatAgeMs <= HEARTBEAT_STALE_MS;
|
|
291
|
+
if (recheck.pidAlive !== false && recheckFresh) {
|
|
292
|
+
const ageSec = Math.round((recheck.heartbeatAgeMs ?? 0) / 1000);
|
|
293
|
+
audit(`\u6740\u524D\u590D\u6838\u6539\u5224 ok\uFF1Apid=${pid} \u5FC3\u8DF3\u5DF2\u6062\u590D\uFF08\u5E74\u9F84 ${ageSec}s\uFF09\uFF0C\u653E\u5F03\u8BEF\u6740`);
|
|
294
|
+
log(`[supervisor] \u6740\u524D\u590D\u6838\u6539\u5224 ok\uFF1A\u5FC3\u8DF3\u5DF2\u6062\u590D\uFF08${ageSec}s\uFF09\uFF0C\u653E\u5F03\u6740 pid=${pid}`);
|
|
295
|
+
return { action: "ok", detail: `\u6740\u524D\u590D\u6838\uFF1A\u5FC3\u8DF3\u5DF2\u6062\u590D\uFF0C\u653E\u5F03\u8BEF\u6740 pid=${pid}`, killedPid: null, spawnedPid: null };
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
kill(pid, "SIGTERM");
|
|
299
|
+
const deadline = now + policy.graceMs;
|
|
300
|
+
let alive = isAlive(pid);
|
|
301
|
+
while (alive && Date.now() < deadline) {
|
|
302
|
+
await sleep(250);
|
|
303
|
+
alive = isAlive(pid);
|
|
304
|
+
}
|
|
305
|
+
if (alive) {
|
|
306
|
+
kill(pid, "SIGKILL");
|
|
307
|
+
const hardDeadline = Date.now() + 3000;
|
|
308
|
+
while (alive && Date.now() < hardDeadline) {
|
|
309
|
+
await sleep(250);
|
|
310
|
+
alive = isAlive(pid);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
if (alive) {
|
|
314
|
+
audit(`give-up-kill\uFF1Apid=${pid} \u65E0\u6CD5\u7EC8\u6B62\uFF08\u6743\u9650/\u7CFB\u7EDF\u7EA7\uFF09\uFF0C\u672C\u6B21\u4E0D\u62C9\u8D77`);
|
|
315
|
+
return { action: "give-up", detail: `pid=${pid} \u65E0\u6CD5\u7EC8\u6B62`, killedPid: null, spawnedPid: null };
|
|
316
|
+
}
|
|
317
|
+
killedPid = pid;
|
|
318
|
+
}
|
|
319
|
+
try {
|
|
320
|
+
const locksDir = dirname(deps.paths.lockPath);
|
|
321
|
+
let cleared = [];
|
|
322
|
+
if (killedPid !== null) {
|
|
323
|
+
cleared = releaseLocksOfPid(killedPid, locksDir);
|
|
324
|
+
} else if (health.pidAlive === false && health.lockPid !== null) {
|
|
325
|
+
cleared = releaseLocksOfPid(health.lockPid, locksDir);
|
|
326
|
+
}
|
|
327
|
+
if (existsSync2(deps.paths.lockPath)) {
|
|
328
|
+
try {
|
|
329
|
+
unlinkSync2(deps.paths.lockPath);
|
|
330
|
+
if (!cleared.includes(deps.paths.lockPath))
|
|
331
|
+
cleared.push(deps.paths.lockPath);
|
|
332
|
+
} catch {}
|
|
333
|
+
}
|
|
334
|
+
if (cleared.length > 0)
|
|
335
|
+
audit(`\u6E05\u9501\uFF1A${cleared.join("\u3001")}\uFF08${action.reason}\uFF09`);
|
|
336
|
+
} catch {}
|
|
337
|
+
const spawnedPid = deps.spawn();
|
|
338
|
+
state.restartLog.push(Date.now());
|
|
339
|
+
state.restartLog = state.restartLog.filter((t) => t > Date.now() - policy.windowMs * 2);
|
|
340
|
+
try {
|
|
341
|
+
writeFileSync2(statePath, JSON.stringify(state));
|
|
342
|
+
} catch {
|
|
343
|
+
log("[supervisor] \u5F3A\u5EA6\u8D26\u843D\u76D8\u5931\u8D25\uFF08\u4E0D\u5F71\u54CD\u672C\u6B21\u62C9\u8D77\uFF09");
|
|
344
|
+
}
|
|
345
|
+
let livenessVerdict = "alive";
|
|
346
|
+
let respawnPid = null;
|
|
347
|
+
if (deps.livenessCheck !== false) {
|
|
348
|
+
const graceWaitMs = 1e4;
|
|
349
|
+
await sleep(graceWaitMs);
|
|
350
|
+
const liveness = readBotHealth(deps.paths, Date.now());
|
|
351
|
+
if (!isPidAlive(spawnedPid) || liveness.lockPid === null) {
|
|
352
|
+
livenessVerdict = `dead-after-spawn\uFF0810s \u590D\u6838\uFF1A\u8FDB\u7A0B${isPidAlive(spawnedPid) ? "\u5728\u4F46\u9501\u672A\u5EFA\u7ACB" : "\u5DF2\u9000\u51FA"}\uFF09`;
|
|
353
|
+
audit(`\u4E8C\u6B21\u8FFD\u51FB\uFF1A\u62C9\u8D77 pid=${spawnedPid} \u5931\u8D25\uFF08${livenessVerdict}\uFF09\uFF0C\u7ACB\u5373\u91CD\u62C9`);
|
|
354
|
+
try {
|
|
355
|
+
const locksDir2 = dirname(deps.paths.lockPath);
|
|
356
|
+
let cleared2 = [];
|
|
357
|
+
if (!isPidAlive(spawnedPid) && existsSync2(deps.paths.lockPath)) {
|
|
358
|
+
cleared2 = releaseLocksOfPid(spawnedPid, locksDir2);
|
|
359
|
+
}
|
|
360
|
+
if (existsSync2(deps.paths.lockPath)) {
|
|
361
|
+
try {
|
|
362
|
+
unlinkSync2(deps.paths.lockPath);
|
|
363
|
+
if (!cleared2.includes(deps.paths.lockPath))
|
|
364
|
+
cleared2.push(deps.paths.lockPath);
|
|
365
|
+
} catch {}
|
|
366
|
+
}
|
|
367
|
+
if (cleared2.length > 0)
|
|
368
|
+
audit(`\u6E05\u9501\uFF1A${cleared2.join("\u3001")}\uFF08\u4E8C\u6B21\u8FFD\u51FB\u524D\u6E05\u573A\uFF09`);
|
|
369
|
+
} catch {}
|
|
370
|
+
respawnPid = deps.spawn();
|
|
371
|
+
await sleep(graceWaitMs);
|
|
372
|
+
const liveness2 = readBotHealth(deps.paths, Date.now());
|
|
373
|
+
if (!isPidAlive(respawnPid) || liveness2.lockPid === null) {
|
|
374
|
+
livenessVerdict += `\uFF1B\u4E8C\u6B21\u62C9\u8D77 pid=${respawnPid} \u4ECD\u5931\u8D25\u2014\u2014\u4EA4\u4E0B\u8F6E\u5DE1\u68C0\u63A5\u529B\uFF08\u5F3A\u5EA6\u8D26 ${state.restartLog.length}/${policy.maxRestarts}\uFF09`;
|
|
375
|
+
} else {
|
|
376
|
+
livenessVerdict += `\uFF1B\u4E8C\u6B21\u62C9\u8D77 pid=${respawnPid} \u6210\u529F`;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
if (killedPid !== null || livenessVerdict !== "alive") {
|
|
381
|
+
appendKillLog({
|
|
382
|
+
kind: "decision",
|
|
383
|
+
reason: action.reason,
|
|
384
|
+
health: {
|
|
385
|
+
lockPid: health.lockPid,
|
|
386
|
+
pidAlive: health.pidAlive,
|
|
387
|
+
heartbeatAgeMs: health.heartbeatAgeMs,
|
|
388
|
+
lockAgeMs: health.lockAgeMs
|
|
389
|
+
},
|
|
390
|
+
killedPid,
|
|
391
|
+
killEscalation: killedPid !== null ? "TERM" : "n/a",
|
|
392
|
+
spawnedPid: respawnPid ?? spawnedPid,
|
|
393
|
+
restartIntensity: `${state.restartLog.length}/${policy.maxRestarts}`,
|
|
394
|
+
livenessVerdict: livenessVerdict !== "alive" ? livenessVerdict : "alive",
|
|
395
|
+
at: Date.now()
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
const detail = `${action.reason}\uFF1B${killedPid ? `\u5DF2\u4F18\u96C5\u505C pid=${killedPid}\uFF1B` : ""}\u5DF2\u62C9\u8D77 pid=${respawnPid ?? spawnedPid}${livenessVerdict !== "alive" ? `\uFF1B${livenessVerdict}` : ""}`;
|
|
399
|
+
audit(killedPid ? `\u4E3B\u52A8\u6740\uFF1A${detail}` : `\u9A8C\u5C38\u62C9\u65B0\uFF1A${detail}`);
|
|
400
|
+
return { action: "restart", detail, killedPid, spawnedPid: respawnPid ?? spawnedPid };
|
|
401
|
+
} finally {
|
|
402
|
+
release();
|
|
25
403
|
}
|
|
26
404
|
}
|
|
27
405
|
|
|
406
|
+
// src/core/bot-control.ts
|
|
407
|
+
import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
|
|
408
|
+
import { dirname as dirname3, join as join4 } from "path";
|
|
409
|
+
import { fileURLToPath } from "url";
|
|
410
|
+
|
|
28
411
|
// src/core/bot-launcher.ts
|
|
29
412
|
import { spawn, spawnSync } from "child_process";
|
|
30
|
-
import { existsSync, readFileSync as
|
|
31
|
-
import { join as
|
|
413
|
+
import { existsSync as existsSync3, readFileSync as readFileSync3, statSync as statSync4 } from "fs";
|
|
414
|
+
import { join as join3, dirname as dirname2, isAbsolute } from "path";
|
|
32
415
|
import { homedir as homedir2 } from "os";
|
|
33
416
|
function resolveRuntime(probe = defaultProbe) {
|
|
34
417
|
if (resolveBunCommand(probe))
|
|
@@ -37,44 +420,103 @@ function resolveRuntime(probe = defaultProbe) {
|
|
|
37
420
|
return "node";
|
|
38
421
|
return null;
|
|
39
422
|
}
|
|
423
|
+
function isExecutable(p) {
|
|
424
|
+
try {
|
|
425
|
+
const st = statSync4(p);
|
|
426
|
+
return st.isFile() && (process.platform === "win32" || (st.mode & 73) !== 0);
|
|
427
|
+
} catch {
|
|
428
|
+
return false;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
function locateOnPath(cmd, pathEnv = process.env.PATH ?? process.env.Path ?? "") {
|
|
432
|
+
if (isAbsolute(cmd))
|
|
433
|
+
return isExecutable(cmd) ? cmd : null;
|
|
434
|
+
const isWin = process.platform === "win32";
|
|
435
|
+
for (const dir of pathEnv.split(isWin ? ";" : ":")) {
|
|
436
|
+
if (!dir)
|
|
437
|
+
continue;
|
|
438
|
+
const base = isWin && !/\.[a-z]+$/i.test(cmd) ? `${cmd}.exe` : cmd;
|
|
439
|
+
const full = join3(dir, base);
|
|
440
|
+
if (isExecutable(full))
|
|
441
|
+
return full;
|
|
442
|
+
}
|
|
443
|
+
if (isWin)
|
|
444
|
+
return resolveThroughShim(cmd, pathEnv);
|
|
445
|
+
return null;
|
|
446
|
+
}
|
|
447
|
+
var SHIM_PATTERN_LINE = /%~?dp0%?\\?([^"\n]+?\.exe)/;
|
|
448
|
+
var SHIM_PATTERN_ABS = /([A-Za-z]:\\[^\n"]+?\.exe)/;
|
|
449
|
+
function resolveThroughShim(bare, pathEnv = process.env.PATH ?? process.env.Path ?? "") {
|
|
450
|
+
for (const dir of pathEnv.split(";")) {
|
|
451
|
+
if (!dir)
|
|
452
|
+
continue;
|
|
453
|
+
for (const ext of [".cmd", ".bat"]) {
|
|
454
|
+
const shimPath = join3(dir, bare + ext);
|
|
455
|
+
let text;
|
|
456
|
+
try {
|
|
457
|
+
text = readFileSync3(shimPath, "utf-8");
|
|
458
|
+
} catch {
|
|
459
|
+
continue;
|
|
460
|
+
}
|
|
461
|
+
const rel = SHIM_PATTERN_LINE.exec(text);
|
|
462
|
+
if (rel) {
|
|
463
|
+
const full = join3(dir, rel[1]);
|
|
464
|
+
if (isExecutable(full))
|
|
465
|
+
return full;
|
|
466
|
+
}
|
|
467
|
+
const abs = SHIM_PATTERN_ABS.exec(text);
|
|
468
|
+
if (abs) {
|
|
469
|
+
const full = abs[1];
|
|
470
|
+
if (isExecutable(full))
|
|
471
|
+
return full;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
return null;
|
|
476
|
+
}
|
|
40
477
|
function bunCandidates() {
|
|
41
|
-
const candidates = ["bun", "bun.exe", "bun.cmd", "bun.bat"];
|
|
42
478
|
if (process.platform === "win32") {
|
|
43
|
-
const appdata = process.env.APPDATA ||
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
479
|
+
const appdata = process.env.APPDATA || join3(homedir2(), "AppData", "Roaming");
|
|
480
|
+
return [
|
|
481
|
+
join3(appdata, "npm", "node_modules", "bun", "bin", "bun.exe"),
|
|
482
|
+
join3(homedir2(), ".bun", "bin", "bun.exe"),
|
|
483
|
+
"bun",
|
|
484
|
+
"bun.exe"
|
|
485
|
+
];
|
|
47
486
|
}
|
|
48
|
-
return
|
|
487
|
+
return ["/usr/local/bin/bun", "/opt/homebrew/bin/bun", join3(homedir2(), ".bun", "bin", "bun"), "bun"];
|
|
49
488
|
}
|
|
50
489
|
function resolveBunCommand(probe = defaultProbe) {
|
|
490
|
+
if (probe !== defaultProbe) {
|
|
491
|
+
for (const c of bunCandidates()) {
|
|
492
|
+
if (!probe(c))
|
|
493
|
+
continue;
|
|
494
|
+
if (isAbsolute(c))
|
|
495
|
+
return c;
|
|
496
|
+
return locateOnPath(c) ?? resolveThroughShim(c) ?? null;
|
|
497
|
+
}
|
|
498
|
+
return null;
|
|
499
|
+
}
|
|
51
500
|
for (const c of bunCandidates()) {
|
|
52
|
-
|
|
53
|
-
|
|
501
|
+
const full = locateOnPath(c) ?? (isAbsolute(c) ? null : resolveThroughShim(c));
|
|
502
|
+
if (full)
|
|
503
|
+
return full;
|
|
54
504
|
}
|
|
55
505
|
return null;
|
|
56
506
|
}
|
|
57
507
|
function defaultProbe(cmd) {
|
|
58
508
|
try {
|
|
59
|
-
const r = spawnSync(cmd, ["--version"], { stdio: "ignore" });
|
|
509
|
+
const r = spawnSync(cmd, ["--version"], { stdio: "ignore", windowsHide: true });
|
|
60
510
|
return r.status === 0;
|
|
61
511
|
} catch {
|
|
62
512
|
return false;
|
|
63
513
|
}
|
|
64
514
|
}
|
|
65
|
-
function
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
join2(homedir2(), ".openqq", "plugin-payload", "bot.js"),
|
|
71
|
-
join2(dir, "..", "dist", "openqq-bot.js"),
|
|
72
|
-
join2(dir, "..", "src", "index.ts")
|
|
73
|
-
];
|
|
74
|
-
for (const c of candidates)
|
|
75
|
-
if (exists(c))
|
|
76
|
-
return c;
|
|
77
|
-
return null;
|
|
515
|
+
function resolveRuntimeCommand(runtime) {
|
|
516
|
+
const cmd = runtime === "bun" ? resolveBunCommand() : locateOnPath("node");
|
|
517
|
+
if (!cmd)
|
|
518
|
+
throw new Error(`\u672A\u627E\u5230 ${runtime} \u53EF\u6267\u884C\u4F53\uFF08\u5168\u8DEF\u5F84\u89E3\u6790\u5931\u8D25\uFF09\uFF0C\u62D2\u7EDD\u751F\u6210\u88F8\u540D\u62C9\u8D77\u8BA1\u5212`);
|
|
519
|
+
return cmd;
|
|
78
520
|
}
|
|
79
521
|
function buildLaunchPlan(runtime, entry, logPath) {
|
|
80
522
|
const CONFIG_KEY = [/^QQ_/, /^OPENCODE_/, /^ALLOWED_USERS$/];
|
|
@@ -92,20 +534,20 @@ function buildLaunchPlan(runtime, entry, logPath) {
|
|
|
92
534
|
...logPath ? { QQ_LOG_FILE: logPath } : {}
|
|
93
535
|
};
|
|
94
536
|
if (runtime === "bun") {
|
|
95
|
-
|
|
96
|
-
return { command: bunCmd, args: ["run", entry], env };
|
|
537
|
+
return { command: resolveRuntimeCommand("bun"), args: ["run", entry], env };
|
|
97
538
|
}
|
|
98
|
-
return { command: "node", args: [entry], env };
|
|
539
|
+
return { command: resolveRuntimeCommand("node"), args: [entry], env };
|
|
99
540
|
}
|
|
100
541
|
function botLogPath() {
|
|
101
|
-
return
|
|
542
|
+
return join3(homedir2(), ".openqq", "openqq.log");
|
|
102
543
|
}
|
|
103
544
|
function spawnBotDetached(plan) {
|
|
104
545
|
const child = spawn(plan.command, plan.args, {
|
|
105
546
|
detached: true,
|
|
106
547
|
stdio: "ignore",
|
|
107
548
|
env: plan.env,
|
|
108
|
-
windowsHide: true
|
|
549
|
+
windowsHide: true,
|
|
550
|
+
shell: false
|
|
109
551
|
});
|
|
110
552
|
child.unref();
|
|
111
553
|
if (typeof child.pid !== "number")
|
|
@@ -114,9 +556,9 @@ function spawnBotDetached(plan) {
|
|
|
114
556
|
}
|
|
115
557
|
function readDotEnvField(envPath, key) {
|
|
116
558
|
try {
|
|
117
|
-
if (!
|
|
559
|
+
if (!existsSync3(envPath))
|
|
118
560
|
return null;
|
|
119
|
-
for (const line of
|
|
561
|
+
for (const line of readFileSync3(envPath, "utf-8").split(`
|
|
120
562
|
`)) {
|
|
121
563
|
const trimmed = line.trim();
|
|
122
564
|
if (!trimmed || trimmed.startsWith("#"))
|
|
@@ -133,18 +575,697 @@ function readDotEnvField(envPath, key) {
|
|
|
133
575
|
}
|
|
134
576
|
}
|
|
135
577
|
|
|
578
|
+
// src/core/bot-control.ts
|
|
579
|
+
function resolveInstalledBotEntry(fromUrl, exists = existsSync4) {
|
|
580
|
+
const here = dirname3(fileURLToPath(fromUrl));
|
|
581
|
+
const candidates = [
|
|
582
|
+
join4(here, "openqq-bot.js"),
|
|
583
|
+
join4(here, "..", "dist", "openqq-bot.js"),
|
|
584
|
+
join4(here, "..", "src", "index.ts"),
|
|
585
|
+
join4(here, "..", "..", "src", "index.ts")
|
|
586
|
+
];
|
|
587
|
+
for (const c of candidates)
|
|
588
|
+
if (exists(c))
|
|
589
|
+
return c;
|
|
590
|
+
return null;
|
|
591
|
+
}
|
|
592
|
+
function startBot(fromUrl, log = () => {}) {
|
|
593
|
+
const entry = resolveInstalledBotEntry(fromUrl);
|
|
594
|
+
if (!entry)
|
|
595
|
+
throw new Error("\u672A\u627E\u5230 bot \u5165\u53E3\uFF08dist/openqq-bot.js \u6216 src/index.ts\uFF09\u2014\u2014\u5B89\u88C5\u4E0D\u5B8C\u6574");
|
|
596
|
+
const runtime = resolveRuntime();
|
|
597
|
+
if (!runtime)
|
|
598
|
+
throw new Error("\u672A\u627E\u5230 bun/node \u8FD0\u884C\u65F6");
|
|
599
|
+
const plan = buildLaunchPlan(runtime, entry, botLogPath());
|
|
600
|
+
const pid = spawnBotDetached(plan);
|
|
601
|
+
log(`[bot-control] \u5DF2\u62C9\u8D77 pid=${pid}\uFF08runtime=${runtime}\uFF0Centry=${entry}\uFF09`);
|
|
602
|
+
return pid;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// src/cli/notify.ts
|
|
606
|
+
import { existsSync as existsSync8, readFileSync as readFileSync8 } from "fs";
|
|
607
|
+
|
|
608
|
+
// src/core/storage.ts
|
|
609
|
+
import { homedir as homedir3 } from "os";
|
|
610
|
+
import { join as join5 } from "path";
|
|
611
|
+
var LEGACY_ROOT = join5(homedir3(), ".openqq");
|
|
612
|
+
function storageRoot(appId) {
|
|
613
|
+
const base = (process.env.QQ_DATA_DIR ?? "").trim() || LEGACY_ROOT;
|
|
614
|
+
return appId ? join5(base, "roles", appId) : base;
|
|
615
|
+
}
|
|
616
|
+
function storageFile(name, appId) {
|
|
617
|
+
return join5(storageRoot(appId), name);
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
// src/core/outbox.ts
|
|
621
|
+
import {
|
|
622
|
+
closeSync as closeSync2,
|
|
623
|
+
existsSync as existsSync5,
|
|
624
|
+
mkdirSync as mkdirSync2,
|
|
625
|
+
openSync as openSync2,
|
|
626
|
+
readFileSync as readFileSync5,
|
|
627
|
+
renameSync as renameSync2,
|
|
628
|
+
statSync as statSync5,
|
|
629
|
+
unlinkSync as unlinkSync3,
|
|
630
|
+
writeFileSync as writeFileSync3
|
|
631
|
+
} from "fs";
|
|
632
|
+
import { dirname as dirname4 } from "path";
|
|
633
|
+
import { randomUUID } from "crypto";
|
|
634
|
+
var OUTBOX_SENT_RETENTION_MS = 24 * 60 * 60 * 1000;
|
|
635
|
+
var OUTBOX_SENT_RETENTION_LIMIT = 20;
|
|
636
|
+
var OUTBOX_DEFAULT_RETRY_BASE_MS = 1000;
|
|
637
|
+
var OUTBOX_DEFAULT_RETRY_MAX_MS = 60000;
|
|
638
|
+
var DEFAULT_POLL_INTERVAL_MS = 1000;
|
|
639
|
+
var DEFAULT_LEASE_MS = 30000;
|
|
640
|
+
var DEFAULT_LOCK_WAIT_MS = 5000;
|
|
641
|
+
var DEFAULT_LOCK_STALE_MS = 30000;
|
|
642
|
+
var sleepArray = new Int32Array(new SharedArrayBuffer(4));
|
|
643
|
+
function nonNegative(value, fallback, name) {
|
|
644
|
+
const resolved = value ?? fallback;
|
|
645
|
+
if (!Number.isFinite(resolved) || resolved < 0)
|
|
646
|
+
throw new Error(`${name} \u5FC5\u987B\u662F >= 0 \u7684\u6709\u9650\u6570`);
|
|
647
|
+
return resolved;
|
|
648
|
+
}
|
|
649
|
+
function positive(value, fallback, name) {
|
|
650
|
+
const resolved = nonNegative(value, fallback, name);
|
|
651
|
+
if (resolved === 0)
|
|
652
|
+
throw new Error(`${name} \u5FC5\u987B > 0`);
|
|
653
|
+
return resolved;
|
|
654
|
+
}
|
|
655
|
+
function errorText(error) {
|
|
656
|
+
return error instanceof Error ? error.message : String(error);
|
|
657
|
+
}
|
|
658
|
+
function jsonSnapshot(value, label) {
|
|
659
|
+
const encoded = JSON.stringify(value);
|
|
660
|
+
if (encoded === undefined)
|
|
661
|
+
throw new Error(`Outbox ${label} \u5FC5\u987B\u662F\u53EF JSON \u5E8F\u5217\u5316\u7684\u503C`);
|
|
662
|
+
return JSON.parse(encoded);
|
|
663
|
+
}
|
|
664
|
+
function delay(ms) {
|
|
665
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
666
|
+
}
|
|
667
|
+
function atomicWrite(filePath, document) {
|
|
668
|
+
mkdirSync2(dirname4(filePath), { recursive: true });
|
|
669
|
+
const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
|
|
670
|
+
try {
|
|
671
|
+
writeFileSync3(temporary, JSON.stringify(document, null, 2), { mode: 384 });
|
|
672
|
+
renameSync2(temporary, filePath);
|
|
673
|
+
} catch (error) {
|
|
674
|
+
try {
|
|
675
|
+
unlinkSync3(temporary);
|
|
676
|
+
} catch {}
|
|
677
|
+
throw error;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
function readDocument(filePath, now) {
|
|
681
|
+
if (!existsSync5(filePath))
|
|
682
|
+
return { version: 1, entries: [] };
|
|
683
|
+
const raw = JSON.parse(readFileSync5(filePath, "utf8"));
|
|
684
|
+
if (Array.isArray(raw)) {
|
|
685
|
+
return { version: 1, entries: pruneOutboxEntries(raw, now) };
|
|
686
|
+
}
|
|
687
|
+
if (typeof raw !== "object" || raw === null || raw.version !== 1 || !Array.isArray(raw.entries)) {
|
|
688
|
+
throw new Error(`Outbox \u6587\u4EF6\u683C\u5F0F\u65E0\u6548: ${filePath}`);
|
|
689
|
+
}
|
|
690
|
+
const entries = raw.entries;
|
|
691
|
+
return { version: 1, entries: pruneOutboxEntries(entries, now) };
|
|
692
|
+
}
|
|
693
|
+
function pruneOutboxEntries(entries, now = Date.now()) {
|
|
694
|
+
const indexed = entries.map((entry, index) => ({ entry, index }));
|
|
695
|
+
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));
|
|
696
|
+
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);
|
|
697
|
+
}
|
|
698
|
+
function createOutbox(options = {}) {
|
|
699
|
+
const filePath = options.filePath ?? process.env.QQ_OUTBOX_FILE ?? storageFile("outbox.json");
|
|
700
|
+
const pollIntervalMs = nonNegative(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, "pollIntervalMs");
|
|
701
|
+
const retryBaseMs = nonNegative(options.retryBaseMs, OUTBOX_DEFAULT_RETRY_BASE_MS, "retryBaseMs");
|
|
702
|
+
const retryMaxMs = nonNegative(options.retryMaxMs, OUTBOX_DEFAULT_RETRY_MAX_MS, "retryMaxMs");
|
|
703
|
+
const leaseMs = positive(options.leaseMs, DEFAULT_LEASE_MS, "leaseMs");
|
|
704
|
+
const lockWaitMs = positive(options.lockWaitMs, DEFAULT_LOCK_WAIT_MS, "lockWaitMs");
|
|
705
|
+
const lockStaleMs = positive(options.lockStaleMs, DEFAULT_LOCK_STALE_MS, "lockStaleMs");
|
|
706
|
+
const owner = `${process.pid}:${randomUUID()}`;
|
|
707
|
+
const handlers = new Map;
|
|
708
|
+
const inFlight = new Map;
|
|
709
|
+
const automatic = new Set;
|
|
710
|
+
let timer;
|
|
711
|
+
let stopped = false;
|
|
712
|
+
let flushing;
|
|
713
|
+
function withLock(fn) {
|
|
714
|
+
mkdirSync2(dirname4(filePath), { recursive: true });
|
|
715
|
+
const lockPath = `${filePath}.lock`;
|
|
716
|
+
const token = `${owner}:${Date.now()}:${randomUUID()}`;
|
|
717
|
+
const deadline = Date.now() + lockWaitMs;
|
|
718
|
+
for (;; ) {
|
|
719
|
+
try {
|
|
720
|
+
const fd = openSync2(lockPath, "wx", 384);
|
|
721
|
+
try {
|
|
722
|
+
writeFileSync3(fd, token);
|
|
723
|
+
} finally {
|
|
724
|
+
closeSync2(fd);
|
|
725
|
+
}
|
|
726
|
+
break;
|
|
727
|
+
} catch (error) {
|
|
728
|
+
try {
|
|
729
|
+
if (Date.now() - statSync5(lockPath).mtimeMs > lockStaleMs)
|
|
730
|
+
unlinkSync3(lockPath);
|
|
731
|
+
} catch {}
|
|
732
|
+
if (Date.now() >= deadline)
|
|
733
|
+
throw new Error(`Outbox \u9501\u7B49\u5F85\u8D85\u65F6: ${errorText(error)}`);
|
|
734
|
+
Atomics.wait(sleepArray, 0, 0, 10);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
try {
|
|
738
|
+
return fn();
|
|
739
|
+
} finally {
|
|
740
|
+
try {
|
|
741
|
+
if (readFileSync5(lockPath, "utf8") === token)
|
|
742
|
+
unlinkSync3(lockPath);
|
|
743
|
+
} catch {}
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
function mutate(fn) {
|
|
747
|
+
return withLock(() => {
|
|
748
|
+
const document = readDocument(filePath, Date.now());
|
|
749
|
+
const result = fn(document.entries);
|
|
750
|
+
document.entries = pruneOutboxEntries(document.entries);
|
|
751
|
+
atomicWrite(filePath, document);
|
|
752
|
+
return result;
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
function clone(entry) {
|
|
756
|
+
return JSON.parse(JSON.stringify(entry));
|
|
757
|
+
}
|
|
758
|
+
function clearLease(entry) {
|
|
759
|
+
delete entry.leaseOwner;
|
|
760
|
+
delete entry.leaseUntil;
|
|
761
|
+
}
|
|
762
|
+
function transitionRecovered(entry, now, maxAttempts) {
|
|
763
|
+
if (entry.state !== "sending")
|
|
764
|
+
return false;
|
|
765
|
+
const exhausted = maxAttempts !== undefined && entry.attempts >= maxAttempts;
|
|
766
|
+
entry.state = exhausted ? "failed" : "pending";
|
|
767
|
+
entry.updatedAt = now;
|
|
768
|
+
entry.nextAttemptAt = now;
|
|
769
|
+
entry.lastError = exhausted ? `${entry.lastError ? `${entry.lastError}; ` : ""}\u5D29\u6E83\u6062\u590D\u540E\u5DF2\u8FBE\u5230 maxAttempts=${maxAttempts}` : "\u8FDB\u7A0B\u5728 sending \u671F\u95F4\u9000\u51FA\uFF0C\u53D1\u9001\u7ED3\u679C\u672A\u77E5\uFF1B\u6309\u81F3\u5C11\u4E00\u6B21\u8BED\u4E49\u6062\u590D";
|
|
770
|
+
clearLease(entry);
|
|
771
|
+
return true;
|
|
772
|
+
}
|
|
773
|
+
async function recover(recoverOptions = {}) {
|
|
774
|
+
const now = Date.now();
|
|
775
|
+
return mutate((entries) => {
|
|
776
|
+
const recovered = [];
|
|
777
|
+
const exhausted = [];
|
|
778
|
+
for (const entry of entries) {
|
|
779
|
+
if (entry.state !== "sending")
|
|
780
|
+
continue;
|
|
781
|
+
if (inFlight.has(entry.id) && entry.leaseOwner?.startsWith(`${owner}:`))
|
|
782
|
+
continue;
|
|
783
|
+
const expired = entry.leaseUntil === undefined || entry.leaseUntil <= now;
|
|
784
|
+
if (!recoverOptions.ignoreLeases && !expired)
|
|
785
|
+
continue;
|
|
786
|
+
transitionRecovered(entry, now, recoverOptions.maxAttempts);
|
|
787
|
+
const snapshot = clone(entry);
|
|
788
|
+
if (snapshot.state === "failed")
|
|
789
|
+
exhausted.push(snapshot);
|
|
790
|
+
else
|
|
791
|
+
recovered.push(snapshot);
|
|
792
|
+
}
|
|
793
|
+
return { recovered, exhausted };
|
|
794
|
+
});
|
|
795
|
+
}
|
|
796
|
+
async function dispatchInternal(id, dispatchOptions) {
|
|
797
|
+
const handlerlessSnapshot = readDocument(filePath, Date.now()).entries.find((entry) => entry.id === id);
|
|
798
|
+
if (!handlerlessSnapshot)
|
|
799
|
+
return null;
|
|
800
|
+
const handler = handlers.get(handlerlessSnapshot.kind);
|
|
801
|
+
if (!handler)
|
|
802
|
+
return clone(handlerlessSnapshot);
|
|
803
|
+
const now = Date.now();
|
|
804
|
+
const token = `${owner}:${randomUUID()}`;
|
|
805
|
+
const claimed = withLock(() => {
|
|
806
|
+
const document = readDocument(filePath, now);
|
|
807
|
+
const entry = document.entries.find((candidate) => candidate.id === id);
|
|
808
|
+
if (!entry)
|
|
809
|
+
return { entry: null };
|
|
810
|
+
if (entry.state === "sent")
|
|
811
|
+
return { entry: clone(entry) };
|
|
812
|
+
if (entry.state === "sending" && entry.leaseUntil !== undefined && entry.leaseUntil > now) {
|
|
813
|
+
return { entry: null };
|
|
814
|
+
}
|
|
815
|
+
if ((entry.state === "pending" || entry.state === "failed" || entry.state === "sending") && !dispatchOptions.force && entry.nextAttemptAt > now) {
|
|
816
|
+
return { entry: clone(entry) };
|
|
817
|
+
}
|
|
818
|
+
const maxAttempts = dispatchOptions.maxAttempts;
|
|
819
|
+
if (maxAttempts !== undefined && entry.attempts >= maxAttempts) {
|
|
820
|
+
if (entry.state !== "failed") {
|
|
821
|
+
entry.state = "failed";
|
|
822
|
+
entry.updatedAt = now;
|
|
823
|
+
clearLease(entry);
|
|
824
|
+
atomicWrite(filePath, document);
|
|
825
|
+
}
|
|
826
|
+
return { entry: clone(entry) };
|
|
827
|
+
}
|
|
828
|
+
entry.state = "sending";
|
|
829
|
+
entry.attempts += 1;
|
|
830
|
+
entry.updatedAt = now;
|
|
831
|
+
entry.leaseOwner = token;
|
|
832
|
+
entry.leaseUntil = now + leaseMs;
|
|
833
|
+
delete entry.lastError;
|
|
834
|
+
atomicWrite(filePath, document);
|
|
835
|
+
return { entry: clone(entry), token };
|
|
836
|
+
});
|
|
837
|
+
if (!claimed.entry || !("token" in claimed))
|
|
838
|
+
return claimed.entry;
|
|
839
|
+
try {
|
|
840
|
+
const receipt = await handler(clone(claimed.entry));
|
|
841
|
+
const persistedReceipt = receipt === undefined ? null : jsonSnapshot(receipt, "receipt");
|
|
842
|
+
return mutate((entries) => {
|
|
843
|
+
const current = entries.find((entry) => entry.id === id);
|
|
844
|
+
if (!current || current.leaseOwner !== token)
|
|
845
|
+
return current ? clone(current) : null;
|
|
846
|
+
const completedAt = Date.now();
|
|
847
|
+
current.state = "sent";
|
|
848
|
+
current.updatedAt = completedAt;
|
|
849
|
+
current.receipt = persistedReceipt;
|
|
850
|
+
delete current.lastError;
|
|
851
|
+
clearLease(current);
|
|
852
|
+
return clone(current);
|
|
853
|
+
});
|
|
854
|
+
} catch (error) {
|
|
855
|
+
const failed = mutate((entries) => {
|
|
856
|
+
const current = entries.find((entry) => entry.id === id);
|
|
857
|
+
if (!current || current.leaseOwner !== token)
|
|
858
|
+
return current ? clone(current) : null;
|
|
859
|
+
const failedAt = Date.now();
|
|
860
|
+
current.state = "failed";
|
|
861
|
+
current.updatedAt = failedAt;
|
|
862
|
+
current.lastError = errorText(error);
|
|
863
|
+
current.nextAttemptAt = failedAt + Math.min(retryMaxMs, retryBaseMs * 2 ** Math.max(0, current.attempts - 1));
|
|
864
|
+
clearLease(current);
|
|
865
|
+
return clone(current);
|
|
866
|
+
});
|
|
867
|
+
if (automatic.has(id))
|
|
868
|
+
return failed;
|
|
869
|
+
throw error;
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
function dispatch(id, dispatchOptions = {}) {
|
|
873
|
+
const existing = inFlight.get(id);
|
|
874
|
+
if (existing)
|
|
875
|
+
return existing;
|
|
876
|
+
const promise = dispatchInternal(id, dispatchOptions).finally(() => {
|
|
877
|
+
if (inFlight.get(id) === promise)
|
|
878
|
+
inFlight.delete(id);
|
|
879
|
+
});
|
|
880
|
+
inFlight.set(id, promise);
|
|
881
|
+
return promise;
|
|
882
|
+
}
|
|
883
|
+
async function flush(flushOptions = {}) {
|
|
884
|
+
if (flushing)
|
|
885
|
+
return flushing;
|
|
886
|
+
const run = (async () => {
|
|
887
|
+
const results = new Map;
|
|
888
|
+
for (;; ) {
|
|
889
|
+
await recover({ maxAttempts: flushOptions.maxAttempts });
|
|
890
|
+
const entries = readDocument(filePath, Date.now()).entries;
|
|
891
|
+
const candidates = entries.filter((entry) => {
|
|
892
|
+
if (entry.state !== "pending" && entry.state !== "failed")
|
|
893
|
+
return false;
|
|
894
|
+
if (!handlers.has(entry.kind))
|
|
895
|
+
return false;
|
|
896
|
+
if (flushOptions.maxAttempts !== undefined && entry.attempts >= flushOptions.maxAttempts)
|
|
897
|
+
return false;
|
|
898
|
+
return flushOptions.force || flushOptions.wait || entry.nextAttemptAt <= Date.now();
|
|
899
|
+
});
|
|
900
|
+
const settled = await Promise.all(candidates.map(async (entry) => {
|
|
901
|
+
const result = await dispatch(entry.id, flushOptions);
|
|
902
|
+
if (result)
|
|
903
|
+
results.set(entry.id, result);
|
|
904
|
+
return result;
|
|
905
|
+
}));
|
|
906
|
+
if (!flushOptions.wait)
|
|
907
|
+
break;
|
|
908
|
+
const after = readDocument(filePath, Date.now()).entries;
|
|
909
|
+
const active = after.filter((entry) => (entry.state === "pending" || entry.state === "failed") && handlers.has(entry.kind) && (flushOptions.maxAttempts === undefined || entry.attempts < flushOptions.maxAttempts));
|
|
910
|
+
const waitingLocal = after.some((entry) => entry.state === "sending" && inFlight.has(entry.id));
|
|
911
|
+
if (active.length === 0 && !waitingLocal)
|
|
912
|
+
break;
|
|
913
|
+
if (settled.length === 0 && !waitingLocal) {
|
|
914
|
+
const next = active.reduce((minimum, entry) => Math.min(minimum, entry.nextAttemptAt), Number.POSITIVE_INFINITY);
|
|
915
|
+
if (Number.isFinite(next))
|
|
916
|
+
await delay(Math.max(1, next - Date.now()));
|
|
917
|
+
else
|
|
918
|
+
break;
|
|
919
|
+
} else {
|
|
920
|
+
await delay(1);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
return [...results.values()];
|
|
924
|
+
})();
|
|
925
|
+
flushing = run;
|
|
926
|
+
try {
|
|
927
|
+
return await run;
|
|
928
|
+
} finally {
|
|
929
|
+
if (flushing === run)
|
|
930
|
+
flushing = undefined;
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
async function drain() {
|
|
934
|
+
while (inFlight.size > 0) {
|
|
935
|
+
const pending = [...inFlight.values()];
|
|
936
|
+
const outcomes = await Promise.allSettled(pending);
|
|
937
|
+
const rejection = outcomes.find((outcome) => outcome.status === "rejected");
|
|
938
|
+
if (rejection)
|
|
939
|
+
throw rejection.reason;
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
return {
|
|
943
|
+
filePath,
|
|
944
|
+
register(kind, handler) {
|
|
945
|
+
if (!kind)
|
|
946
|
+
throw new Error("Outbox kind \u4E0D\u80FD\u4E3A\u7A7A");
|
|
947
|
+
handlers.set(kind, handler);
|
|
948
|
+
return () => {
|
|
949
|
+
if (handlers.get(kind) === handler)
|
|
950
|
+
handlers.delete(kind);
|
|
951
|
+
};
|
|
952
|
+
},
|
|
953
|
+
async enqueue(input) {
|
|
954
|
+
if (!input.kind)
|
|
955
|
+
throw new Error("Outbox kind \u4E0D\u80FD\u4E3A\u7A7A");
|
|
956
|
+
if (input.payload === undefined)
|
|
957
|
+
throw new Error("Outbox payload \u5FC5\u987B\u662F JSON \u503C\uFF0C\u4E0D\u80FD\u4E3A undefined");
|
|
958
|
+
if (input.nextAttemptAt !== undefined && !Number.isFinite(input.nextAttemptAt)) {
|
|
959
|
+
throw new Error("Outbox nextAttemptAt \u5FC5\u987B\u662F\u6709\u9650\u65F6\u95F4\u6233");
|
|
960
|
+
}
|
|
961
|
+
const persistedCtx = jsonSnapshot(input.ctx, "ctx");
|
|
962
|
+
const persistedPayload = jsonSnapshot(input.payload, "payload");
|
|
963
|
+
const now = Date.now();
|
|
964
|
+
const id = input.id ?? randomUUID();
|
|
965
|
+
const entry = mutate((entries) => {
|
|
966
|
+
const existing = entries.find((candidate) => candidate.id === id);
|
|
967
|
+
if (existing)
|
|
968
|
+
return clone(existing);
|
|
969
|
+
const created = {
|
|
970
|
+
id,
|
|
971
|
+
kind: input.kind,
|
|
972
|
+
ctx: persistedCtx,
|
|
973
|
+
payload: persistedPayload,
|
|
974
|
+
...input.sessionId !== undefined ? { sessionId: input.sessionId } : {},
|
|
975
|
+
...input.turnId !== undefined ? { turnId: input.turnId } : {},
|
|
976
|
+
state: "pending",
|
|
977
|
+
attempts: 0,
|
|
978
|
+
createdAt: now,
|
|
979
|
+
updatedAt: now,
|
|
980
|
+
nextAttemptAt: input.nextAttemptAt ?? now
|
|
981
|
+
};
|
|
982
|
+
entries.push(created);
|
|
983
|
+
return clone(created);
|
|
984
|
+
});
|
|
985
|
+
automatic.add(id);
|
|
986
|
+
dispatch(id).finally(() => automatic.delete(id)).catch(() => {});
|
|
987
|
+
return entry;
|
|
988
|
+
},
|
|
989
|
+
dispatch,
|
|
990
|
+
recover,
|
|
991
|
+
flush,
|
|
992
|
+
async start(startOptions = {}) {
|
|
993
|
+
stopped = false;
|
|
994
|
+
if (startOptions.recover !== false)
|
|
995
|
+
await recover({ maxAttempts: startOptions.maxAttempts });
|
|
996
|
+
if (pollIntervalMs === 0 || timer)
|
|
997
|
+
return;
|
|
998
|
+
timer = setInterval(() => {
|
|
999
|
+
if (stopped)
|
|
1000
|
+
return;
|
|
1001
|
+
flush({ maxAttempts: startOptions.maxAttempts }).catch(() => {});
|
|
1002
|
+
}, pollIntervalMs);
|
|
1003
|
+
timer.unref?.();
|
|
1004
|
+
flush({ maxAttempts: startOptions.maxAttempts }).catch(() => {});
|
|
1005
|
+
},
|
|
1006
|
+
stop() {
|
|
1007
|
+
stopped = true;
|
|
1008
|
+
if (timer)
|
|
1009
|
+
clearInterval(timer);
|
|
1010
|
+
timer = undefined;
|
|
1011
|
+
},
|
|
1012
|
+
drain,
|
|
1013
|
+
async list() {
|
|
1014
|
+
return readDocument(filePath, Date.now()).entries.map((entry) => clone(entry));
|
|
1015
|
+
},
|
|
1016
|
+
async get(id) {
|
|
1017
|
+
const entry = readDocument(filePath, Date.now()).entries.find((candidate) => candidate.id === id);
|
|
1018
|
+
return entry ? clone(entry) : undefined;
|
|
1019
|
+
}
|
|
1020
|
+
};
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
// src/config.ts
|
|
1024
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync7, writeFileSync as writeFileSync4 } from "fs";
|
|
1025
|
+
import { join as join7 } from "path";
|
|
1026
|
+
import { homedir as homedir5 } from "os";
|
|
1027
|
+
|
|
1028
|
+
// src/core/bot-config.ts
|
|
1029
|
+
import { existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
|
|
1030
|
+
import { homedir as homedir4 } from "os";
|
|
1031
|
+
import { join as join6 } from "path";
|
|
1032
|
+
function configJsonPath(env = process.env) {
|
|
1033
|
+
return env.QQ_CONFIG_FILE?.trim() || join6(homedir4(), ".openqq", "config.json");
|
|
1034
|
+
}
|
|
1035
|
+
function parseConfigJson(raw) {
|
|
1036
|
+
let parsed;
|
|
1037
|
+
try {
|
|
1038
|
+
parsed = JSON.parse(raw);
|
|
1039
|
+
} catch {
|
|
1040
|
+
console.warn("[config] config.json \u4E0D\u662F\u5408\u6CD5 JSON\uFF0C\u5DF2\u5FFD\u7565");
|
|
1041
|
+
return {};
|
|
1042
|
+
}
|
|
1043
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
1044
|
+
console.warn("[config] config.json \u5FC5\u987B\u662F\u5E73\u94FA JSON \u5BF9\u8C61\uFF0C\u5DF2\u5FFD\u7565");
|
|
1045
|
+
return {};
|
|
1046
|
+
}
|
|
1047
|
+
const out = {};
|
|
1048
|
+
for (const [k, v] of Object.entries(parsed)) {
|
|
1049
|
+
if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
|
|
1050
|
+
out[k] = String(v);
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
return out;
|
|
1054
|
+
}
|
|
1055
|
+
function computeOverlay(env, config) {
|
|
1056
|
+
return Object.entries(config).filter(([k]) => env[k] === undefined);
|
|
1057
|
+
}
|
|
1058
|
+
function applyConfigOverlay(env = process.env) {
|
|
1059
|
+
const path = configJsonPath(env);
|
|
1060
|
+
if (!existsSync6(path))
|
|
1061
|
+
return 0;
|
|
1062
|
+
let raw;
|
|
1063
|
+
try {
|
|
1064
|
+
raw = readFileSync6(path, "utf-8");
|
|
1065
|
+
} catch {
|
|
1066
|
+
return 0;
|
|
1067
|
+
}
|
|
1068
|
+
const overlay = computeOverlay(env, parseConfigJson(raw));
|
|
1069
|
+
for (const [k, v] of overlay)
|
|
1070
|
+
env[k] = v;
|
|
1071
|
+
if (overlay.length > 0) {
|
|
1072
|
+
console.log(`[config] config.json \u5DF2\u53E0\u52A0 ${overlay.length} \u9879\uFF08env/.env \u4F18\u5148\uFF09: ${path}`);
|
|
1073
|
+
}
|
|
1074
|
+
return overlay.length;
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
// src/config.ts
|
|
1078
|
+
var CONFIG_DIR = join7(homedir5(), ".openqq");
|
|
1079
|
+
var ENV_FILE = join7(CONFIG_DIR, ".env");
|
|
1080
|
+
function loadEnvFile(path) {
|
|
1081
|
+
const content = readFileSync7(path, "utf-8");
|
|
1082
|
+
for (const line of content.split(`
|
|
1083
|
+
`)) {
|
|
1084
|
+
const trimmed = line.trim();
|
|
1085
|
+
if (!trimmed || trimmed.startsWith("#"))
|
|
1086
|
+
continue;
|
|
1087
|
+
const eqIdx = trimmed.indexOf("=");
|
|
1088
|
+
if (eqIdx < 0)
|
|
1089
|
+
continue;
|
|
1090
|
+
const key = trimmed.slice(0, eqIdx).trim();
|
|
1091
|
+
const val = trimmed.slice(eqIdx + 1).trim();
|
|
1092
|
+
if (!process.env[key]) {
|
|
1093
|
+
process.env[key] = val;
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
// src/core/notify-sink.ts
|
|
1099
|
+
function resolveNotifyRecipients(configured, explicit) {
|
|
1100
|
+
const users = [...configured];
|
|
1101
|
+
if (explicit)
|
|
1102
|
+
return users.includes(explicit) ? explicit : "";
|
|
1103
|
+
return users.length === 1 ? users[0] : "";
|
|
1104
|
+
}
|
|
1105
|
+
function defaultOutboxPath() {
|
|
1106
|
+
return storageFile("outbox.json");
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
// src/cli/notify.ts
|
|
1110
|
+
var NOTIFY_DEFAULT_MAX_CHARS = 1500;
|
|
1111
|
+
function parseArgs(argv) {
|
|
1112
|
+
const parsed = { maxChars: NOTIFY_DEFAULT_MAX_CHARS, dryRun: false, json: false, help: false };
|
|
1113
|
+
for (let i = 0;i < argv.length; i++) {
|
|
1114
|
+
const a = argv[i];
|
|
1115
|
+
const next = argv[i + 1];
|
|
1116
|
+
switch (a) {
|
|
1117
|
+
case "--text":
|
|
1118
|
+
parsed.text = next;
|
|
1119
|
+
i++;
|
|
1120
|
+
break;
|
|
1121
|
+
case "--file":
|
|
1122
|
+
parsed.filePath = next;
|
|
1123
|
+
i++;
|
|
1124
|
+
break;
|
|
1125
|
+
case "--stdin":
|
|
1126
|
+
parsed.stdin = true;
|
|
1127
|
+
break;
|
|
1128
|
+
case "--user":
|
|
1129
|
+
parsed.user = next;
|
|
1130
|
+
i++;
|
|
1131
|
+
break;
|
|
1132
|
+
case "--id":
|
|
1133
|
+
parsed.id = next;
|
|
1134
|
+
i++;
|
|
1135
|
+
break;
|
|
1136
|
+
case "--max-chars":
|
|
1137
|
+
parsed.maxChars = Number(next);
|
|
1138
|
+
i++;
|
|
1139
|
+
break;
|
|
1140
|
+
case "--ttl-hours":
|
|
1141
|
+
parsed.ttlHours = Number(next);
|
|
1142
|
+
i++;
|
|
1143
|
+
break;
|
|
1144
|
+
case "--dry-run":
|
|
1145
|
+
parsed.dryRun = true;
|
|
1146
|
+
break;
|
|
1147
|
+
case "--json":
|
|
1148
|
+
parsed.json = true;
|
|
1149
|
+
break;
|
|
1150
|
+
case "--help":
|
|
1151
|
+
case "-h":
|
|
1152
|
+
parsed.help = true;
|
|
1153
|
+
i++;
|
|
1154
|
+
break;
|
|
1155
|
+
default:
|
|
1156
|
+
throw new Error(`\u672A\u77E5\u53C2\u6570\uFF1A${a}\uFF08\u7528\u6CD5\uFF1Aopenqq notify --text "\u2026" | --file <p> | --stdin\uFF09`);
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
if (!parsed.help && !parsed.text && !parsed.filePath && !parsed.stdin) {
|
|
1160
|
+
throw new Error("\u5FC5\u987B\u63D0\u4F9B\u6B63\u6587\u6765\u6E90\uFF1A--text / --file / --stdin \u4E09\u9009\u4E00");
|
|
1161
|
+
}
|
|
1162
|
+
if (!Number.isFinite(parsed.maxChars) || parsed.maxChars < 0) {
|
|
1163
|
+
throw new Error("--max-chars \u5FC5\u987B\u662F >= 0 \u7684\u6709\u9650\u6570\uFF080=\u4E0D\u622A\u65AD\uFF09");
|
|
1164
|
+
}
|
|
1165
|
+
return parsed;
|
|
1166
|
+
}
|
|
1167
|
+
function resolveUser(envAllowed, explicit) {
|
|
1168
|
+
return resolveNotifyRecipients(envAllowed, explicit);
|
|
1169
|
+
}
|
|
1170
|
+
function readBody(parsed) {
|
|
1171
|
+
if (parsed.text !== undefined)
|
|
1172
|
+
return parsed.text;
|
|
1173
|
+
if (parsed.filePath !== undefined) {
|
|
1174
|
+
if (parsed.filePath === "-")
|
|
1175
|
+
return readFileSync8(0, "utf8");
|
|
1176
|
+
if (!existsSync8(parsed.filePath))
|
|
1177
|
+
throw new Error(`--file \u4E0D\u5B58\u5728\uFF1A${parsed.filePath}`);
|
|
1178
|
+
return readFileSync8(parsed.filePath, "utf8");
|
|
1179
|
+
}
|
|
1180
|
+
if (parsed.stdin)
|
|
1181
|
+
return readFileSync8(0, "utf8");
|
|
1182
|
+
return "";
|
|
1183
|
+
}
|
|
1184
|
+
async function runNotifyCli(argv, options = {}) {
|
|
1185
|
+
const now = options.now ?? Date.now();
|
|
1186
|
+
const parsed = parseArgs(argv);
|
|
1187
|
+
if (parsed.help) {
|
|
1188
|
+
const help = [
|
|
1189
|
+
'\u7528\u6CD5\uFF1Aopenqq notify --text "\u2026" | --file <\u8DEF\u5F84> | --stdin',
|
|
1190
|
+
" --user <openid> \u6536\u4EF6\u4EBA\uFF1B\u7F3A\u7701\u53D6 ALLOWED_USERS \u552F\u4E00\u9879\uFF08\u591A\u7528\u6237\u5FC5\u987B\u663E\u5F0F\u6307\u5B9A\uFF09",
|
|
1191
|
+
" --id <key> \u5E42\u7B49\u952E\uFF08\u540C key \u4E0D\u91CD\u590D\u6295\u9012\uFF09",
|
|
1192
|
+
" --max-chars <n> \u622A\u65AD\u4E0A\u9650\uFF0C\u9ED8\u8BA4 1500\uFF0C0 \u4E0D\u622A\u65AD",
|
|
1193
|
+
" --ttl-hours <n> \u961F\u5217\u7B49\u5F85\u4E0A\u9650\uFF0C\u9ED8\u8BA4 24\uFF08env QQ_NOTIFY_TTL_HOURS \u515C\u5E95\uFF09",
|
|
1194
|
+
" --dry-run / --json \u4E0D\u5165\u961F / \u673A\u5668\u53EF\u8BFB\u8F93\u51FA"
|
|
1195
|
+
].join(`
|
|
1196
|
+
`);
|
|
1197
|
+
console.log(help);
|
|
1198
|
+
return { ok: true, queued: false, id: "", user: "", chars: 0, truncated: false, dryRun: true, json: parsed.json, reason: "help" };
|
|
1199
|
+
}
|
|
1200
|
+
applyConfigOverlay();
|
|
1201
|
+
if (!options.env && existsSync8(ENV_FILE))
|
|
1202
|
+
loadEnvFile(ENV_FILE);
|
|
1203
|
+
const allowedUsers = options.env ? [...options.env.allowedUsers] : String(process.env.ALLOWED_USERS ?? "").split(/[,\s]+/).filter(Boolean);
|
|
1204
|
+
const user = resolveUser(allowedUsers, parsed.user);
|
|
1205
|
+
if (!user) {
|
|
1206
|
+
throw new Error(allowedUsers.length === 0 ? "ALLOWED_USERS \u4E3A\u7A7A\u2014\u2014fail-closed \u4E0D\u5141\u8BB8\u65E0\u540D\u5355\u5165\u961F\uFF08\u5148\u5728 ~/.openqq/.env \u914D\u7F6E\uFF09" : parsed.user ? `\u6536\u4EF6\u4EBA\u4E0D\u5728\u540D\u5355\uFF1A${parsed.user}\uFF08ALLOWED_USERS \u5171 ${allowedUsers.length} \u9879\uFF0C--user \u5FC5\u987B\u7CBE\u786E\u547D\u4E2D\uFF1B\u8BF7\u6838\u5BF9 openid\uFF09` : "\u591A\u7528\u6237\u540D\u5355\u5FC5\u987B\u7528 --user <openid> \u663E\u5F0F\u6307\u5B9A\u6536\u4EF6\u4EBA");
|
|
1207
|
+
}
|
|
1208
|
+
const raw = readBody(parsed);
|
|
1209
|
+
const max = parsed.maxChars;
|
|
1210
|
+
const content = max === 0 ? raw : raw.length > max ? `${raw.slice(0, max)}\u2026` : raw;
|
|
1211
|
+
const id = parsed.id || `notify-${now.toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
1212
|
+
const filePath = options.filePath ?? defaultOutboxPath();
|
|
1213
|
+
if (parsed.dryRun) {
|
|
1214
|
+
return { ok: true, queued: false, id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: true, json: parsed.json };
|
|
1215
|
+
}
|
|
1216
|
+
const ttlHours = parsed.ttlHours ?? Number(process.env.QQ_NOTIFY_TTL_HOURS ?? 24);
|
|
1217
|
+
const nextAttemptAt = parsed.ttlHours !== undefined && Number.isFinite(ttlHours) && ttlHours > 0 ? now + ttlHours * 60 * 60 * 1000 : now;
|
|
1218
|
+
const outbox = createOutbox({ filePath, pollIntervalMs: 0 });
|
|
1219
|
+
const entry = await outbox.enqueue({
|
|
1220
|
+
...parsed.id ? { id: parsed.id } : {},
|
|
1221
|
+
kind: "notify",
|
|
1222
|
+
payload: { text: content },
|
|
1223
|
+
ctx: { type: "c2c", userId: user, msgId: "", content: "(openqq notify)", timestamp: String(now) },
|
|
1224
|
+
sessionId: "",
|
|
1225
|
+
nextAttemptAt
|
|
1226
|
+
});
|
|
1227
|
+
return { ok: true, queued: true, id: entry.id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: false, json: parsed.json };
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
// src/core/supervisor-election.ts
|
|
1231
|
+
import { readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "fs";
|
|
1232
|
+
import { join as join8 } from "path";
|
|
1233
|
+
import { homedir as homedir6 } from "os";
|
|
1234
|
+
var LEASE_PATH = join8(homedir6(), ".openqq", "supervisor-lease.json");
|
|
1235
|
+
var LEASE_TTL_MS = 10 * 60000;
|
|
1236
|
+
function electSupervisor(channel, opts) {
|
|
1237
|
+
const ttlMs = opts?.ttlMs ?? LEASE_TTL_MS;
|
|
1238
|
+
const now = opts?.now ?? Date.now();
|
|
1239
|
+
const path = opts?.path ?? LEASE_PATH;
|
|
1240
|
+
try {
|
|
1241
|
+
let cur = null;
|
|
1242
|
+
try {
|
|
1243
|
+
cur = JSON.parse(readFileSync9(path, "utf-8"));
|
|
1244
|
+
} catch {}
|
|
1245
|
+
if (cur && typeof cur.until === "number" && cur.until > now) {
|
|
1246
|
+
const mine = cur.channel === channel && cur.pid === process.pid;
|
|
1247
|
+
if (!mine)
|
|
1248
|
+
return false;
|
|
1249
|
+
}
|
|
1250
|
+
writeFileSync5(path, JSON.stringify({ channel, pid: process.pid, until: now + ttlMs }));
|
|
1251
|
+
return true;
|
|
1252
|
+
} catch {
|
|
1253
|
+
return true;
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
|
|
136
1257
|
// src/plugin-entry.ts
|
|
137
|
-
var
|
|
1258
|
+
var ENV_FILE2 = join9(homedir7(), ".openqq", ".env");
|
|
138
1259
|
var CHECK_INTERVAL_MS = (() => {
|
|
139
1260
|
const n = Number(process.env.QQ_WATCHDOG_INTERVAL_MS ?? "300000");
|
|
140
1261
|
return Number.isFinite(n) && n > 0 ? n : 300000;
|
|
141
1262
|
})();
|
|
142
|
-
var PROBE_FILE =
|
|
1263
|
+
var PROBE_FILE = join9(homedir7(), ".openqq", "opencode-events.jsonl");
|
|
143
1264
|
var PROBE_ROTATE_BYTES = 5 * 1024 * 1024;
|
|
144
1265
|
function probeAppend(line) {
|
|
145
1266
|
try {
|
|
146
|
-
if (
|
|
147
|
-
|
|
1267
|
+
if (existsSync9(PROBE_FILE) && statSync6(PROBE_FILE).size > PROBE_ROTATE_BYTES) {
|
|
1268
|
+
renameSync3(PROBE_FILE, PROBE_FILE + ".1");
|
|
148
1269
|
}
|
|
149
1270
|
appendFileSync(PROBE_FILE, line + `
|
|
150
1271
|
`);
|
|
@@ -162,28 +1283,41 @@ var plugin_entry_default = Plugin.define({
|
|
|
162
1283
|
};
|
|
163
1284
|
const ensure = () => {
|
|
164
1285
|
try {
|
|
165
|
-
const
|
|
1286
|
+
const botsRaw = readDotEnvField(ENV_FILE2, "QQ_BOTS");
|
|
1287
|
+
let botsFirst = null;
|
|
1288
|
+
if (botsRaw) {
|
|
1289
|
+
try {
|
|
1290
|
+
const arr = JSON.parse(botsRaw);
|
|
1291
|
+
const first = Array.isArray(arr) ? arr[0]?.appId : undefined;
|
|
1292
|
+
if (typeof first === "string" && first)
|
|
1293
|
+
botsFirst = first;
|
|
1294
|
+
} catch {}
|
|
1295
|
+
}
|
|
1296
|
+
const appId = readDotEnvField(ENV_FILE2, "QQ_APP_ID") ?? botsFirst;
|
|
166
1297
|
if (!appId) {
|
|
167
1298
|
warnOnce("cred", "[opencode-qqbot] \u672A\u53D1\u73B0 ~/.openqq/.env \u51ED\u636E\u2014\u2014\u5148\u8FD0\u884C npx @linjz/opencode-qqbot setup \u626B\u7801\u7ED1\u5B9A\uFF08\u6216\u53C2\u8003 README \u624B\u5199 .env\uFF09\uFF0C\u5B8C\u6210\u540E\u63D2\u4EF6\u5C06\u5728\u4E0B\u6B21\u5DE1\u68C0\u81EA\u52A8\u62C9\u8D77 bot");
|
|
168
1299
|
return;
|
|
169
1300
|
}
|
|
170
|
-
if (
|
|
171
|
-
lastBlocker = null;
|
|
1301
|
+
if (!electSupervisor("plugin"))
|
|
172
1302
|
return;
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
1303
|
+
superviseOnce({
|
|
1304
|
+
paths: botWatchdogPaths(appId),
|
|
1305
|
+
spawn: () => startBot(fileURLToPath2(import.meta.url), (line) => console.log(line)),
|
|
1306
|
+
log: (line) => console.log(line),
|
|
1307
|
+
alert: (message) => {
|
|
1308
|
+
console.warn(message);
|
|
1309
|
+
runNotifyCli(["--text", message, "--id", `supervisor-giveup-${Date.now()}`]).catch(() => {});
|
|
1310
|
+
}
|
|
1311
|
+
}).then((result) => {
|
|
1312
|
+
if (result.action === "restart") {
|
|
1313
|
+
console.log(`[opencode-qqbot] bot \u5DF2\u62C9\u8D77\uFF08${result.detail}\uFF09`);
|
|
1314
|
+
}
|
|
1315
|
+
if (result.action === "ok" || result.action === "restart")
|
|
1316
|
+
lastBlocker = null;
|
|
1317
|
+
}).catch((error) => {
|
|
1318
|
+
appendWatchdogLog(`[plugin] \u5DE1\u68C0\u5931\u8D25: ${error instanceof Error ? error.message : String(error)}`);
|
|
1319
|
+
console.error("[opencode-qqbot] \u5DE1\u68C0\u5931\u8D25:", error instanceof Error ? error.message : error);
|
|
1320
|
+
});
|
|
187
1321
|
} catch (error) {
|
|
188
1322
|
console.error("[opencode-qqbot] \u62C9\u8D77\u5931\u8D25:", error instanceof Error ? error.message : error);
|
|
189
1323
|
}
|
|
@@ -191,7 +1325,7 @@ var plugin_entry_default = Plugin.define({
|
|
|
191
1325
|
ensure();
|
|
192
1326
|
const timer = setInterval(ensure, CHECK_INTERVAL_MS);
|
|
193
1327
|
let probeAbort = null;
|
|
194
|
-
if (readDotEnvField(
|
|
1328
|
+
if (readDotEnvField(ENV_FILE2, "QQ_EVENT_PROBE") === "true") {
|
|
195
1329
|
probeAbort = new AbortController;
|
|
196
1330
|
const signal = probeAbort.signal;
|
|
197
1331
|
(async () => {
|