@linjz/opencode-qqbot 0.3.16 → 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 -266
- package/README.zh-CN.md +313 -0
- package/dist/notify-cli.js +64 -12
- package/dist/opencode-qqbot-plugin.js +356 -92
- package/dist/openqq-bot.js +878 -226
- package/dist/openqq-cli.js +253 -64
- package/dist/openqq-watchdog.js +373 -110
- package/package.json +2 -2
- package/src/bridge.ts +292 -3
- package/src/cli/notify.ts +4 -1
- package/src/cli/watchdog-main.ts +22 -7
- package/src/commands.ts +36 -10
- package/src/config.ts +39 -5
- package/src/core/bot-config.ts +66 -0
- package/src/core/bot-control.ts +21 -3
- package/src/core/bot-launcher.ts +4 -2
- package/src/core/cron-reminders.ts +84 -0
- package/src/core/discovery.ts +207 -169
- package/src/core/error-rescue.ts +1 -1
- package/src/core/file-log.ts +16 -7
- package/src/core/inflight-journal.ts +1 -0
- package/src/core/instance-lock.ts +32 -1
- package/src/core/log-rotate.ts +91 -0
- package/src/core/mirror.ts +7 -1
- package/src/core/notices.ts +62 -0
- package/src/core/outbound-sanitize.ts +29 -0
- package/src/core/permission.ts +7 -0
- package/src/core/queue-view.ts +1 -0
- package/src/core/send-media.ts +29 -2
- package/src/core/start-error.ts +26 -0
- package/src/core/stt.ts +55 -0
- package/src/core/supervisor-election.ts +53 -0
- package/src/core/watchdog.ts +171 -14
- package/src/index.ts +262 -250
- package/src/opencode/client.ts +32 -1
- package/src/opencode/mirror.ts +10 -3
- package/src/plugin-entry.ts +21 -2
- package/src/qq/gateway.ts +35 -0
- package/src/qq/media.ts +21 -0
- package/src/qq/sender.ts +50 -1
|
@@ -1,19 +1,110 @@
|
|
|
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
|
|
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
7
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
8
8
|
|
|
9
9
|
// src/core/watchdog.ts
|
|
10
|
-
import { readFileSync, statSync, unlinkSync, writeFileSync } from "fs";
|
|
11
|
-
import { join } from "path";
|
|
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
|
+
// 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
|
+
}
|
|
52
|
+
}
|
|
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 {}
|
|
75
|
+
}
|
|
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;
|
|
82
|
+
try {
|
|
83
|
+
names = readdirSync(dir);
|
|
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
|
|
13
104
|
var HEARTBEAT_STALE_MS = 5 * 60000;
|
|
14
105
|
function botWatchdogPaths(appId) {
|
|
15
|
-
const dir =
|
|
16
|
-
return { lockPath:
|
|
106
|
+
const dir = join2(homedir(), ".openqq");
|
|
107
|
+
return { lockPath: join2(dir, `openqq-${appId}.lock`), heartbeatPath: join2(dir, "heartbeat") };
|
|
17
108
|
}
|
|
18
109
|
function isPidAlive(pid) {
|
|
19
110
|
if (!Number.isInteger(pid) || pid <= 0)
|
|
@@ -27,7 +118,7 @@ function isPidAlive(pid) {
|
|
|
27
118
|
}
|
|
28
119
|
function ageOf(path, now) {
|
|
29
120
|
try {
|
|
30
|
-
return Math.max(0, now -
|
|
121
|
+
return Math.max(0, now - statSync3(path).mtimeMs);
|
|
31
122
|
} catch {
|
|
32
123
|
return null;
|
|
33
124
|
}
|
|
@@ -37,7 +128,7 @@ function readBotHealth(paths, now = Date.now()) {
|
|
|
37
128
|
let lockPid = null;
|
|
38
129
|
if (lockAgeMs !== null) {
|
|
39
130
|
try {
|
|
40
|
-
const raw = JSON.parse(
|
|
131
|
+
const raw = JSON.parse(readFileSync2(paths.lockPath, "utf-8"));
|
|
41
132
|
if (typeof raw.pid === "number" && Number.isInteger(raw.pid))
|
|
42
133
|
lockPid = raw.pid;
|
|
43
134
|
} catch {}
|
|
@@ -51,11 +142,27 @@ function readBotHealth(paths, now = Date.now()) {
|
|
|
51
142
|
}
|
|
52
143
|
function appendWatchdogLog(line) {
|
|
53
144
|
try {
|
|
54
|
-
const
|
|
55
|
-
|
|
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}
|
|
56
152
|
`, { flag: "a" });
|
|
57
153
|
} catch {}
|
|
58
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
|
+
}
|
|
59
166
|
var DEFAULT_SUPERVISOR_POLICY = {
|
|
60
167
|
cooldownMs: 2 * 60000,
|
|
61
168
|
maxRestarts: 3,
|
|
@@ -92,7 +199,7 @@ var defaultSupervisorKill = (pid, signal) => {
|
|
|
92
199
|
};
|
|
93
200
|
function readJson(path, fallback) {
|
|
94
201
|
try {
|
|
95
|
-
return { ...fallback, ...JSON.parse(
|
|
202
|
+
return { ...fallback, ...JSON.parse(readFileSync2(path, "utf-8")) };
|
|
96
203
|
} catch {
|
|
97
204
|
return fallback;
|
|
98
205
|
}
|
|
@@ -104,12 +211,12 @@ async function superviseOnce(deps) {
|
|
|
104
211
|
const sleep = deps.sleep ?? defaultSleep;
|
|
105
212
|
const kill = deps.kill ?? defaultSupervisorKill;
|
|
106
213
|
const isAlive = deps.isAlive ?? isPidAlive;
|
|
107
|
-
const statePath = deps.statePath ??
|
|
108
|
-
const claimPath = deps.claimPath ??
|
|
214
|
+
const statePath = deps.statePath ?? join2(homedir(), ".openqq", "supervisor.json");
|
|
215
|
+
const claimPath = deps.claimPath ?? join2(homedir(), ".openqq", "supervisor.lock");
|
|
109
216
|
const audit = (line) => {
|
|
110
217
|
if (deps.auditLogPath) {
|
|
111
218
|
try {
|
|
112
|
-
|
|
219
|
+
writeFileSync2(deps.auditLogPath, `${new Date().toISOString()} ${line}
|
|
113
220
|
`, { flag: "a" });
|
|
114
221
|
return;
|
|
115
222
|
} catch {}
|
|
@@ -121,13 +228,13 @@ async function superviseOnce(deps) {
|
|
|
121
228
|
return { action: "yield", detail: `\u76D1\u7763\u8005 pid=${claim.pid} \u6301\u9501\u4E2D`, killedPid: null, spawnedPid: null };
|
|
122
229
|
}
|
|
123
230
|
try {
|
|
124
|
-
|
|
231
|
+
writeFileSync2(claimPath, JSON.stringify({ pid: process.pid, ts: now }));
|
|
125
232
|
} catch {
|
|
126
233
|
return { action: "yield", detail: "\u8BA4\u9886\u9501\u4E0D\u53EF\u5199", killedPid: null, spawnedPid: null };
|
|
127
234
|
}
|
|
128
235
|
const release = () => {
|
|
129
236
|
try {
|
|
130
|
-
|
|
237
|
+
writeFileSync2(claimPath, JSON.stringify({ pid: 0, ts: 0 }));
|
|
131
238
|
} catch {}
|
|
132
239
|
};
|
|
133
240
|
try {
|
|
@@ -161,15 +268,15 @@ async function superviseOnce(deps) {
|
|
|
161
268
|
return { action: "yield", detail: action.reason, killedPid: null, spawnedPid: null };
|
|
162
269
|
}
|
|
163
270
|
if (action.kind === "give-up") {
|
|
164
|
-
const message = `\u26A0\uFE0F QQBot \u770B\u95E8\u72D7\u5DF2\
|
|
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`;
|
|
165
272
|
audit(`give-up\uFF1A${message}`);
|
|
166
|
-
log(`[supervisor] give-up\uFF1A${action.restarts} \u6B21\u91CD\u542F\u4ECD\u5F02\u5E38\uFF0C\
|
|
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`);
|
|
167
274
|
const lastAlert = state.alertedAt ?? 0;
|
|
168
275
|
if (now - lastAlert > 30 * 60000) {
|
|
169
276
|
try {
|
|
170
277
|
deps.alert?.(message);
|
|
171
278
|
state.alertedAt = now;
|
|
172
|
-
|
|
279
|
+
writeFileSync2(statePath, JSON.stringify(state));
|
|
173
280
|
} catch {}
|
|
174
281
|
}
|
|
175
282
|
return { action: "give-up", detail: message, killedPid: null, spawnedPid: null };
|
|
@@ -210,36 +317,101 @@ async function superviseOnce(deps) {
|
|
|
210
317
|
killedPid = pid;
|
|
211
318
|
}
|
|
212
319
|
try {
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
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);
|
|
216
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`);
|
|
217
336
|
} catch {}
|
|
218
337
|
const spawnedPid = deps.spawn();
|
|
219
338
|
state.restartLog.push(Date.now());
|
|
220
339
|
state.restartLog = state.restartLog.filter((t) => t > Date.now() - policy.windowMs * 2);
|
|
221
340
|
try {
|
|
222
|
-
|
|
341
|
+
writeFileSync2(statePath, JSON.stringify(state));
|
|
223
342
|
} catch {
|
|
224
343
|
log("[supervisor] \u5F3A\u5EA6\u8D26\u843D\u76D8\u5931\u8D25\uFF08\u4E0D\u5F71\u54CD\u672C\u6B21\u62C9\u8D77\uFF09");
|
|
225
344
|
}
|
|
226
|
-
|
|
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}` : ""}`;
|
|
227
399
|
audit(killedPid ? `\u4E3B\u52A8\u6740\uFF1A${detail}` : `\u9A8C\u5C38\u62C9\u65B0\uFF1A${detail}`);
|
|
228
|
-
return { action: "restart", detail, killedPid, spawnedPid };
|
|
400
|
+
return { action: "restart", detail, killedPid, spawnedPid: respawnPid ?? spawnedPid };
|
|
229
401
|
} finally {
|
|
230
402
|
release();
|
|
231
403
|
}
|
|
232
404
|
}
|
|
233
405
|
|
|
234
406
|
// src/core/bot-control.ts
|
|
235
|
-
import { existsSync as
|
|
236
|
-
import { dirname as
|
|
407
|
+
import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
|
|
408
|
+
import { dirname as dirname3, join as join4 } from "path";
|
|
237
409
|
import { fileURLToPath } from "url";
|
|
238
410
|
|
|
239
411
|
// src/core/bot-launcher.ts
|
|
240
412
|
import { spawn, spawnSync } from "child_process";
|
|
241
|
-
import { existsSync, readFileSync as
|
|
242
|
-
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";
|
|
243
415
|
import { homedir as homedir2 } from "os";
|
|
244
416
|
function resolveRuntime(probe = defaultProbe) {
|
|
245
417
|
if (resolveBunCommand(probe))
|
|
@@ -250,7 +422,7 @@ function resolveRuntime(probe = defaultProbe) {
|
|
|
250
422
|
}
|
|
251
423
|
function isExecutable(p) {
|
|
252
424
|
try {
|
|
253
|
-
const st =
|
|
425
|
+
const st = statSync4(p);
|
|
254
426
|
return st.isFile() && (process.platform === "win32" || (st.mode & 73) !== 0);
|
|
255
427
|
} catch {
|
|
256
428
|
return false;
|
|
@@ -264,7 +436,7 @@ function locateOnPath(cmd, pathEnv = process.env.PATH ?? process.env.Path ?? "")
|
|
|
264
436
|
if (!dir)
|
|
265
437
|
continue;
|
|
266
438
|
const base = isWin && !/\.[a-z]+$/i.test(cmd) ? `${cmd}.exe` : cmd;
|
|
267
|
-
const full =
|
|
439
|
+
const full = join3(dir, base);
|
|
268
440
|
if (isExecutable(full))
|
|
269
441
|
return full;
|
|
270
442
|
}
|
|
@@ -279,16 +451,16 @@ function resolveThroughShim(bare, pathEnv = process.env.PATH ?? process.env.Path
|
|
|
279
451
|
if (!dir)
|
|
280
452
|
continue;
|
|
281
453
|
for (const ext of [".cmd", ".bat"]) {
|
|
282
|
-
const shimPath =
|
|
454
|
+
const shimPath = join3(dir, bare + ext);
|
|
283
455
|
let text;
|
|
284
456
|
try {
|
|
285
|
-
text =
|
|
457
|
+
text = readFileSync3(shimPath, "utf-8");
|
|
286
458
|
} catch {
|
|
287
459
|
continue;
|
|
288
460
|
}
|
|
289
461
|
const rel = SHIM_PATTERN_LINE.exec(text);
|
|
290
462
|
if (rel) {
|
|
291
|
-
const full =
|
|
463
|
+
const full = join3(dir, rel[1]);
|
|
292
464
|
if (isExecutable(full))
|
|
293
465
|
return full;
|
|
294
466
|
}
|
|
@@ -304,15 +476,15 @@ function resolveThroughShim(bare, pathEnv = process.env.PATH ?? process.env.Path
|
|
|
304
476
|
}
|
|
305
477
|
function bunCandidates() {
|
|
306
478
|
if (process.platform === "win32") {
|
|
307
|
-
const appdata = process.env.APPDATA ||
|
|
479
|
+
const appdata = process.env.APPDATA || join3(homedir2(), "AppData", "Roaming");
|
|
308
480
|
return [
|
|
309
|
-
|
|
310
|
-
|
|
481
|
+
join3(appdata, "npm", "node_modules", "bun", "bin", "bun.exe"),
|
|
482
|
+
join3(homedir2(), ".bun", "bin", "bun.exe"),
|
|
311
483
|
"bun",
|
|
312
484
|
"bun.exe"
|
|
313
485
|
];
|
|
314
486
|
}
|
|
315
|
-
return ["/usr/local/bin/bun", "/opt/homebrew/bin/bun",
|
|
487
|
+
return ["/usr/local/bin/bun", "/opt/homebrew/bin/bun", join3(homedir2(), ".bun", "bin", "bun"), "bun"];
|
|
316
488
|
}
|
|
317
489
|
function resolveBunCommand(probe = defaultProbe) {
|
|
318
490
|
if (probe !== defaultProbe) {
|
|
@@ -367,7 +539,7 @@ function buildLaunchPlan(runtime, entry, logPath) {
|
|
|
367
539
|
return { command: resolveRuntimeCommand("node"), args: [entry], env };
|
|
368
540
|
}
|
|
369
541
|
function botLogPath() {
|
|
370
|
-
return
|
|
542
|
+
return join3(homedir2(), ".openqq", "openqq.log");
|
|
371
543
|
}
|
|
372
544
|
function spawnBotDetached(plan) {
|
|
373
545
|
const child = spawn(plan.command, plan.args, {
|
|
@@ -384,9 +556,9 @@ function spawnBotDetached(plan) {
|
|
|
384
556
|
}
|
|
385
557
|
function readDotEnvField(envPath, key) {
|
|
386
558
|
try {
|
|
387
|
-
if (!
|
|
559
|
+
if (!existsSync3(envPath))
|
|
388
560
|
return null;
|
|
389
|
-
for (const line of
|
|
561
|
+
for (const line of readFileSync3(envPath, "utf-8").split(`
|
|
390
562
|
`)) {
|
|
391
563
|
const trimmed = line.trim();
|
|
392
564
|
if (!trimmed || trimmed.startsWith("#"))
|
|
@@ -404,13 +576,13 @@ function readDotEnvField(envPath, key) {
|
|
|
404
576
|
}
|
|
405
577
|
|
|
406
578
|
// src/core/bot-control.ts
|
|
407
|
-
function resolveInstalledBotEntry(fromUrl, exists =
|
|
408
|
-
const here =
|
|
579
|
+
function resolveInstalledBotEntry(fromUrl, exists = existsSync4) {
|
|
580
|
+
const here = dirname3(fileURLToPath(fromUrl));
|
|
409
581
|
const candidates = [
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
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")
|
|
414
586
|
];
|
|
415
587
|
for (const c of candidates)
|
|
416
588
|
if (exists(c))
|
|
@@ -431,33 +603,33 @@ function startBot(fromUrl, log = () => {}) {
|
|
|
431
603
|
}
|
|
432
604
|
|
|
433
605
|
// src/cli/notify.ts
|
|
434
|
-
import { existsSync as
|
|
606
|
+
import { existsSync as existsSync8, readFileSync as readFileSync8 } from "fs";
|
|
435
607
|
|
|
436
608
|
// src/core/storage.ts
|
|
437
609
|
import { homedir as homedir3 } from "os";
|
|
438
|
-
import { join as
|
|
439
|
-
var LEGACY_ROOT =
|
|
610
|
+
import { join as join5 } from "path";
|
|
611
|
+
var LEGACY_ROOT = join5(homedir3(), ".openqq");
|
|
440
612
|
function storageRoot(appId) {
|
|
441
613
|
const base = (process.env.QQ_DATA_DIR ?? "").trim() || LEGACY_ROOT;
|
|
442
|
-
return appId ?
|
|
614
|
+
return appId ? join5(base, "roles", appId) : base;
|
|
443
615
|
}
|
|
444
616
|
function storageFile(name, appId) {
|
|
445
|
-
return
|
|
617
|
+
return join5(storageRoot(appId), name);
|
|
446
618
|
}
|
|
447
619
|
|
|
448
620
|
// src/core/outbox.ts
|
|
449
621
|
import {
|
|
450
|
-
closeSync,
|
|
451
|
-
existsSync as
|
|
452
|
-
mkdirSync,
|
|
453
|
-
openSync,
|
|
454
|
-
readFileSync as
|
|
455
|
-
renameSync,
|
|
456
|
-
statSync as
|
|
457
|
-
unlinkSync as
|
|
458
|
-
writeFileSync as
|
|
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
|
|
459
631
|
} from "fs";
|
|
460
|
-
import { dirname as
|
|
632
|
+
import { dirname as dirname4 } from "path";
|
|
461
633
|
import { randomUUID } from "crypto";
|
|
462
634
|
var OUTBOX_SENT_RETENTION_MS = 24 * 60 * 60 * 1000;
|
|
463
635
|
var OUTBOX_SENT_RETENTION_LIMIT = 20;
|
|
@@ -493,22 +665,22 @@ function delay(ms) {
|
|
|
493
665
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
494
666
|
}
|
|
495
667
|
function atomicWrite(filePath, document) {
|
|
496
|
-
|
|
668
|
+
mkdirSync2(dirname4(filePath), { recursive: true });
|
|
497
669
|
const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
|
|
498
670
|
try {
|
|
499
|
-
|
|
500
|
-
|
|
671
|
+
writeFileSync3(temporary, JSON.stringify(document, null, 2), { mode: 384 });
|
|
672
|
+
renameSync2(temporary, filePath);
|
|
501
673
|
} catch (error) {
|
|
502
674
|
try {
|
|
503
|
-
|
|
675
|
+
unlinkSync3(temporary);
|
|
504
676
|
} catch {}
|
|
505
677
|
throw error;
|
|
506
678
|
}
|
|
507
679
|
}
|
|
508
680
|
function readDocument(filePath, now) {
|
|
509
|
-
if (!
|
|
681
|
+
if (!existsSync5(filePath))
|
|
510
682
|
return { version: 1, entries: [] };
|
|
511
|
-
const raw = JSON.parse(
|
|
683
|
+
const raw = JSON.parse(readFileSync5(filePath, "utf8"));
|
|
512
684
|
if (Array.isArray(raw)) {
|
|
513
685
|
return { version: 1, entries: pruneOutboxEntries(raw, now) };
|
|
514
686
|
}
|
|
@@ -539,23 +711,23 @@ function createOutbox(options = {}) {
|
|
|
539
711
|
let stopped = false;
|
|
540
712
|
let flushing;
|
|
541
713
|
function withLock(fn) {
|
|
542
|
-
|
|
714
|
+
mkdirSync2(dirname4(filePath), { recursive: true });
|
|
543
715
|
const lockPath = `${filePath}.lock`;
|
|
544
716
|
const token = `${owner}:${Date.now()}:${randomUUID()}`;
|
|
545
717
|
const deadline = Date.now() + lockWaitMs;
|
|
546
718
|
for (;; ) {
|
|
547
719
|
try {
|
|
548
|
-
const fd =
|
|
720
|
+
const fd = openSync2(lockPath, "wx", 384);
|
|
549
721
|
try {
|
|
550
|
-
|
|
722
|
+
writeFileSync3(fd, token);
|
|
551
723
|
} finally {
|
|
552
|
-
|
|
724
|
+
closeSync2(fd);
|
|
553
725
|
}
|
|
554
726
|
break;
|
|
555
727
|
} catch (error) {
|
|
556
728
|
try {
|
|
557
|
-
if (Date.now() -
|
|
558
|
-
|
|
729
|
+
if (Date.now() - statSync5(lockPath).mtimeMs > lockStaleMs)
|
|
730
|
+
unlinkSync3(lockPath);
|
|
559
731
|
} catch {}
|
|
560
732
|
if (Date.now() >= deadline)
|
|
561
733
|
throw new Error(`Outbox \u9501\u7B49\u5F85\u8D85\u65F6: ${errorText(error)}`);
|
|
@@ -566,8 +738,8 @@ function createOutbox(options = {}) {
|
|
|
566
738
|
return fn();
|
|
567
739
|
} finally {
|
|
568
740
|
try {
|
|
569
|
-
if (
|
|
570
|
-
|
|
741
|
+
if (readFileSync5(lockPath, "utf8") === token)
|
|
742
|
+
unlinkSync3(lockPath);
|
|
571
743
|
} catch {}
|
|
572
744
|
}
|
|
573
745
|
}
|
|
@@ -849,13 +1021,64 @@ function createOutbox(options = {}) {
|
|
|
849
1021
|
}
|
|
850
1022
|
|
|
851
1023
|
// src/config.ts
|
|
852
|
-
import { existsSync as
|
|
853
|
-
import { join as
|
|
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";
|
|
854
1030
|
import { homedir as homedir4 } from "os";
|
|
855
|
-
|
|
856
|
-
|
|
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");
|
|
857
1080
|
function loadEnvFile(path) {
|
|
858
|
-
const content =
|
|
1081
|
+
const content = readFileSync7(path, "utf-8");
|
|
859
1082
|
for (const line of content.split(`
|
|
860
1083
|
`)) {
|
|
861
1084
|
const trimmed = line.trim();
|
|
@@ -949,13 +1172,13 @@ function readBody(parsed) {
|
|
|
949
1172
|
return parsed.text;
|
|
950
1173
|
if (parsed.filePath !== undefined) {
|
|
951
1174
|
if (parsed.filePath === "-")
|
|
952
|
-
return
|
|
953
|
-
if (!
|
|
1175
|
+
return readFileSync8(0, "utf8");
|
|
1176
|
+
if (!existsSync8(parsed.filePath))
|
|
954
1177
|
throw new Error(`--file \u4E0D\u5B58\u5728\uFF1A${parsed.filePath}`);
|
|
955
|
-
return
|
|
1178
|
+
return readFileSync8(parsed.filePath, "utf8");
|
|
956
1179
|
}
|
|
957
1180
|
if (parsed.stdin)
|
|
958
|
-
return
|
|
1181
|
+
return readFileSync8(0, "utf8");
|
|
959
1182
|
return "";
|
|
960
1183
|
}
|
|
961
1184
|
async function runNotifyCli(argv, options = {}) {
|
|
@@ -974,7 +1197,8 @@ async function runNotifyCli(argv, options = {}) {
|
|
|
974
1197
|
console.log(help);
|
|
975
1198
|
return { ok: true, queued: false, id: "", user: "", chars: 0, truncated: false, dryRun: true, json: parsed.json, reason: "help" };
|
|
976
1199
|
}
|
|
977
|
-
|
|
1200
|
+
applyConfigOverlay();
|
|
1201
|
+
if (!options.env && existsSync8(ENV_FILE))
|
|
978
1202
|
loadEnvFile(ENV_FILE);
|
|
979
1203
|
const allowedUsers = options.env ? [...options.env.allowedUsers] : String(process.env.ALLOWED_USERS ?? "").split(/[,\s]+/).filter(Boolean);
|
|
980
1204
|
const user = resolveUser(allowedUsers, parsed.user);
|
|
@@ -1003,18 +1227,45 @@ async function runNotifyCli(argv, options = {}) {
|
|
|
1003
1227
|
return { ok: true, queued: true, id: entry.id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: false, json: parsed.json };
|
|
1004
1228
|
}
|
|
1005
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
|
+
|
|
1006
1257
|
// src/plugin-entry.ts
|
|
1007
|
-
var ENV_FILE2 =
|
|
1258
|
+
var ENV_FILE2 = join9(homedir7(), ".openqq", ".env");
|
|
1008
1259
|
var CHECK_INTERVAL_MS = (() => {
|
|
1009
1260
|
const n = Number(process.env.QQ_WATCHDOG_INTERVAL_MS ?? "300000");
|
|
1010
1261
|
return Number.isFinite(n) && n > 0 ? n : 300000;
|
|
1011
1262
|
})();
|
|
1012
|
-
var PROBE_FILE =
|
|
1263
|
+
var PROBE_FILE = join9(homedir7(), ".openqq", "opencode-events.jsonl");
|
|
1013
1264
|
var PROBE_ROTATE_BYTES = 5 * 1024 * 1024;
|
|
1014
1265
|
function probeAppend(line) {
|
|
1015
1266
|
try {
|
|
1016
|
-
if (
|
|
1017
|
-
|
|
1267
|
+
if (existsSync9(PROBE_FILE) && statSync6(PROBE_FILE).size > PROBE_ROTATE_BYTES) {
|
|
1268
|
+
renameSync3(PROBE_FILE, PROBE_FILE + ".1");
|
|
1018
1269
|
}
|
|
1019
1270
|
appendFileSync(PROBE_FILE, line + `
|
|
1020
1271
|
`);
|
|
@@ -1032,11 +1283,23 @@ var plugin_entry_default = Plugin.define({
|
|
|
1032
1283
|
};
|
|
1033
1284
|
const ensure = () => {
|
|
1034
1285
|
try {
|
|
1035
|
-
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;
|
|
1036
1297
|
if (!appId) {
|
|
1037
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");
|
|
1038
1299
|
return;
|
|
1039
1300
|
}
|
|
1301
|
+
if (!electSupervisor("plugin"))
|
|
1302
|
+
return;
|
|
1040
1303
|
superviseOnce({
|
|
1041
1304
|
paths: botWatchdogPaths(appId),
|
|
1042
1305
|
spawn: () => startBot(fileURLToPath2(import.meta.url), (line) => console.log(line)),
|
|
@@ -1052,6 +1315,7 @@ var plugin_entry_default = Plugin.define({
|
|
|
1052
1315
|
if (result.action === "ok" || result.action === "restart")
|
|
1053
1316
|
lastBlocker = null;
|
|
1054
1317
|
}).catch((error) => {
|
|
1318
|
+
appendWatchdogLog(`[plugin] \u5DE1\u68C0\u5931\u8D25: ${error instanceof Error ? error.message : String(error)}`);
|
|
1055
1319
|
console.error("[opencode-qqbot] \u5DE1\u68C0\u5931\u8D25:", error instanceof Error ? error.message : error);
|
|
1056
1320
|
});
|
|
1057
1321
|
} catch (error) {
|