@linjz/opencode-qqbot 0.3.16 → 0.3.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +316 -266
- package/README.zh-CN.md +326 -0
- package/dist/notify-cli.js +64 -12
- package/dist/opencode-qqbot-plugin.js +591 -92
- package/dist/openqq-bot.js +1172 -303
- package/dist/openqq-cli.js +253 -64
- package/dist/openqq-watchdog.js +373 -110
- package/package.json +4 -3
- package/src/bridge.ts +448 -32
- package/src/cli/notify.ts +4 -1
- package/src/cli/watchdog-main.ts +22 -7
- package/src/commands.ts +74 -58
- 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/delivery.ts +24 -1
- 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 +13 -4
- package/src/core/notices.ts +62 -0
- package/src/core/outbound-sanitize.ts +29 -0
- package/src/core/permission.ts +16 -0
- package/src/core/qq-instructions.ts +122 -0
- package/src/core/queue-view.ts +1 -0
- package/src/core/send-media.ts +29 -2
- package/src/core/send-requests.ts +227 -0
- 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/turn-correction.ts +68 -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 +17 -4
- package/src/opencode/sessions.ts +20 -1
- package/src/plugin-entry.ts +67 -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 join12 } from "path";
|
|
5
|
+
import { homedir as homedir8 } from "os";
|
|
6
|
+
import { appendFileSync, existsSync as existsSync11, renameSync as renameSync4, statSync as statSync7 } 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,9 +142,25 @@ 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}
|
|
152
|
+
`, { flag: "a" });
|
|
153
|
+
} catch {}
|
|
154
|
+
}
|
|
155
|
+
function appendKillLog(entry, logPath = join2(homedir(), ".openqq", "kills.log")) {
|
|
156
|
+
try {
|
|
157
|
+
writeFileSync2(logPath, `${JSON.stringify(entry)}
|
|
56
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
|
+
}
|
|
57
164
|
} catch {}
|
|
58
165
|
}
|
|
59
166
|
var DEFAULT_SUPERVISOR_POLICY = {
|
|
@@ -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);
|
|
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 {}
|
|
216
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,257 @@ 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
|
+
|
|
1257
|
+
// src/core/send-requests.ts
|
|
1258
|
+
import { existsSync as existsSync9, mkdirSync as mkdirSync4, readdirSync as readdirSync2, readFileSync as readFileSync10, renameSync as renameSync3, statSync as statSync6, writeFileSync as writeFileSync6 } from "fs";
|
|
1259
|
+
import { join as join10 } from "path";
|
|
1260
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
1261
|
+
|
|
1262
|
+
// src/core/send-media.ts
|
|
1263
|
+
import { resolve, extname, basename, sep, join as join9 } from "path";
|
|
1264
|
+
import { homedir as homedir7 } from "os";
|
|
1265
|
+
|
|
1266
|
+
// src/qq/media.ts
|
|
1267
|
+
var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
|
1268
|
+
|
|
1269
|
+
// src/qq/api.ts
|
|
1270
|
+
var appSandboxRegistry = new Map;
|
|
1271
|
+
var tokenCache = new Map;
|
|
1272
|
+
var tokenFetchByApp = new Map;
|
|
1273
|
+
var appIdByToken = new Map;
|
|
1274
|
+
var backgroundRefreshApps = new Set;
|
|
1275
|
+
|
|
1276
|
+
// src/core/send-media.ts
|
|
1277
|
+
var MAX_SEND_BYTES = 20 * 1024 * 1024;
|
|
1278
|
+
var SEND_DENIED_NAMES = new Set([
|
|
1279
|
+
".env",
|
|
1280
|
+
"credentials",
|
|
1281
|
+
"secrets",
|
|
1282
|
+
"id_rsa",
|
|
1283
|
+
"id_dsa",
|
|
1284
|
+
"id_ecdsa",
|
|
1285
|
+
"id_ed25519",
|
|
1286
|
+
".npmrc",
|
|
1287
|
+
".pypirc",
|
|
1288
|
+
"netrc"
|
|
1289
|
+
]);
|
|
1290
|
+
var SEND_DENIED_EXTS = new Set([".pem", ".key", ".p12", ".pfx", ".kdbx", ".htpasswd"]);
|
|
1291
|
+
function normalizeLocalPath(p) {
|
|
1292
|
+
let r = p.trim();
|
|
1293
|
+
if (r.startsWith("file://")) {
|
|
1294
|
+
r = r.slice("file://".length);
|
|
1295
|
+
if (/^\/[a-zA-Z]:[\\/]/.test(r))
|
|
1296
|
+
r = r.slice(1);
|
|
1297
|
+
}
|
|
1298
|
+
try {
|
|
1299
|
+
r = decodeURIComponent(r);
|
|
1300
|
+
} catch {}
|
|
1301
|
+
if (r === "~" || r.startsWith("~/") || r.startsWith("~\\")) {
|
|
1302
|
+
r = join9(homedir7(), r.slice(1));
|
|
1303
|
+
}
|
|
1304
|
+
return r;
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
// src/core/send-requests.ts
|
|
1308
|
+
function sendRequestsDirFor(appId) {
|
|
1309
|
+
return join10(storageRoot(appId), "send-requests");
|
|
1310
|
+
}
|
|
1311
|
+
function findQQBinding(sessionId, root = storageRoot()) {
|
|
1312
|
+
const candidates = [{ file: join10(root, "sessions.json") }];
|
|
1313
|
+
const rolesDir = join10(root, "roles");
|
|
1314
|
+
if (existsSync9(rolesDir)) {
|
|
1315
|
+
for (const role of readdirSync2(rolesDir)) {
|
|
1316
|
+
candidates.push({ file: join10(rolesDir, role, "sessions.json"), appId: role });
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
for (const { file, appId } of candidates) {
|
|
1320
|
+
try {
|
|
1321
|
+
const parsed = JSON.parse(readFileSync10(file, "utf-8"));
|
|
1322
|
+
for (const [userId, v] of Object.entries(parsed)) {
|
|
1323
|
+
if (v?.sessionId === sessionId)
|
|
1324
|
+
return appId ? { userId, appId } : { userId };
|
|
1325
|
+
}
|
|
1326
|
+
} catch {}
|
|
1327
|
+
}
|
|
1328
|
+
return null;
|
|
1329
|
+
}
|
|
1330
|
+
function dedupeKeyOf(sessionId, normalizedPath, st) {
|
|
1331
|
+
return `${sessionId}:${normalizedPath}:${st.mtimeMs}:${st.size}`;
|
|
1332
|
+
}
|
|
1333
|
+
function writeSendRequest(dir, req) {
|
|
1334
|
+
mkdirSync4(dir, { recursive: true });
|
|
1335
|
+
const tmp = join10(dir, `${req.id}.tmp`);
|
|
1336
|
+
writeFileSync6(tmp, JSON.stringify(req), "utf-8");
|
|
1337
|
+
renameSync3(tmp, join10(dir, `${req.id}.json`));
|
|
1338
|
+
return join10(dir, `${req.id}.json`);
|
|
1339
|
+
}
|
|
1340
|
+
async function awaitSendResult(dir, id, opts = {}) {
|
|
1341
|
+
const timeoutMs = opts.timeoutMs ?? 45000;
|
|
1342
|
+
const intervalMs = opts.intervalMs ?? 500;
|
|
1343
|
+
const file = join10(dir, `${id}.result.json`);
|
|
1344
|
+
const deadline = Date.now() + timeoutMs;
|
|
1345
|
+
for (;; ) {
|
|
1346
|
+
if (existsSync9(file)) {
|
|
1347
|
+
try {
|
|
1348
|
+
return JSON.parse(readFileSync10(file, "utf-8"));
|
|
1349
|
+
} catch {}
|
|
1350
|
+
}
|
|
1351
|
+
if (opts.signal?.aborted)
|
|
1352
|
+
return null;
|
|
1353
|
+
if (Date.now() >= deadline)
|
|
1354
|
+
return null;
|
|
1355
|
+
await new Promise((r) => setTimeout(r, intervalMs));
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
async function executeQQSendFile(input, context) {
|
|
1359
|
+
const binding = findQQBinding(context.sessionID);
|
|
1360
|
+
if (!binding) {
|
|
1361
|
+
return "\u53D1\u9001\u5931\u8D25\uFF1A\u6B64 OpenCode \u4F1A\u8BDD\u672A\u7ED1\u5B9A QQ \u7528\u6237\u2014\u2014\u53EA\u6709\u4ECE QQ \u53D1\u8D77\u7684\u4F1A\u8BDD\uFF08\u6216\u5DF2 /sessions \u5207\u5165\u7ED1\u5B9A\u4F1A\u8BDD\uFF09\u624D\u80FD\u53D1\u9001\u5230 QQ\u3002";
|
|
1362
|
+
}
|
|
1363
|
+
const normalized = normalizeLocalPath(input.path);
|
|
1364
|
+
let st;
|
|
1365
|
+
try {
|
|
1366
|
+
const s = statSync6(normalized);
|
|
1367
|
+
st = { mtimeMs: s.mtimeMs, size: s.size };
|
|
1368
|
+
} catch {
|
|
1369
|
+
return `\u53D1\u9001\u5931\u8D25\uFF1A\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB\u2014\u2014${normalized}\uFF08\u8BF7\u5148\u7528\u5199\u6587\u4EF6\u5DE5\u5177\u751F\u6210\u5230\u672C\u673A\u7EDD\u5BF9\u8DEF\u5F84\uFF0C\u518D\u8C03\u7528\u672C\u5DE5\u5177\uFF09`;
|
|
1370
|
+
}
|
|
1371
|
+
const dir = sendRequestsDirFor(binding.appId);
|
|
1372
|
+
const req = {
|
|
1373
|
+
id: randomUUID2(),
|
|
1374
|
+
sessionId: context.sessionID,
|
|
1375
|
+
userId: binding.userId,
|
|
1376
|
+
appId: binding.appId,
|
|
1377
|
+
path: normalized,
|
|
1378
|
+
caption: input.caption,
|
|
1379
|
+
at: Date.now(),
|
|
1380
|
+
dedupeKey: dedupeKeyOf(context.sessionID, normalized, st)
|
|
1381
|
+
};
|
|
1382
|
+
writeSendRequest(dir, req);
|
|
1383
|
+
const result = await awaitSendResult(dir, req.id, { signal: context.signal });
|
|
1384
|
+
if (!result) {
|
|
1385
|
+
return "\u8BF7\u6C42\u5DF2\u53D7\u7406\u4F46 45s \u5185\u672A\u83B7\u56DE\u6267\u2014\u2014\u53D1\u9001\u7ED3\u679C\u672A\u77E5\uFF08bot \u53EF\u80FD\u5FD9\u6216\u79BB\u7EBF\uFF0C\u6062\u590D\u540E\u4ECD\u4F1A\u6D88\u8D39\uFF09\u3002\u8BF7\u52FF\u76F2\u76EE\u91CD\u8BD5\uFF1B\u53EF\u5148 /status \u6838\u67E5 bot \u72B6\u6001\u3002";
|
|
1386
|
+
}
|
|
1387
|
+
if (result.ok)
|
|
1388
|
+
return `\u5DF2\u53D1\u9001\u5230 QQ\uFF1A${result.detail ?? req.path}${result.deduped ? "\uFF08\u76F8\u540C\u6587\u4EF6\u6B64\u524D\u5DF2\u53D1\uFF0C\u672C\u6B21\u53BB\u91CD\u672A\u91CD\u590D\u53D1\u9001\uFF09" : ""}`;
|
|
1389
|
+
return `\u53D1\u9001\u5931\u8D25\uFF1A${result.error ?? "\u672A\u77E5\u539F\u56E0"}\u2014\u2014\u8BF7\u6309\u539F\u56E0\u4FEE\u6B63\u540E\u91CD\u8BD5\uFF08\u82E5\u662F\u767D\u540D\u5355\u62D2\u7EDD\uFF0C\u53EF\u5148\u628A\u6587\u4EF6\u590D\u5236\u5230\u5141\u8BB8\u7684\u6839\u76EE\u5F55\u5185\u518D\u53D1\uFF09\u3002`;
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
// src/core/qq-instructions.ts
|
|
1393
|
+
import { existsSync as existsSync10, mkdirSync as mkdirSync5, readdirSync as readdirSync3, readFileSync as readFileSync11, writeFileSync as writeFileSync7 } from "fs";
|
|
1394
|
+
import { dirname as dirname5, join as join11 } from "path";
|
|
1395
|
+
var QQ_INSTRUCTION_KEY = "qq";
|
|
1396
|
+
var QQ_INSTRUCTION_TEXT = [
|
|
1397
|
+
"\u672C\u5BF9\u8BDD\u7ECF QQ \u6E32\u67D3\uFF1A",
|
|
1398
|
+
"- \u8F93\u51FA\u683C\u5F0F\uFF1A\u7528\u300C1\u30012\u30013\u3001\u300D\u987F\u53F7\u6216\u300C-\u300D\u65E0\u5E8F\u5217\u8868\u4EE3\u66FF markdown \u6709\u5E8F\u5217\u8868\uFF0C\u907F\u514D\u8868\u683C\uFF1B\u4EE3\u7801\u5757\u4E0D\u53D7\u5F71\u54CD\u53EF\u6B63\u5E38\u4F7F\u7528\u3002",
|
|
1399
|
+
"- \u53D1\u9001\u672C\u673A\u6587\u4EF6/\u56FE\u7247\u7ED9 QQ \u7528\u6237\uFF1A\u4F18\u5148\u8C03\u7528 qq_send_file \u5DE5\u5177\uFF08\u82E5\u5DE5\u5177\u6E05\u5355\u63D0\u4F9B\uFF0C\u5931\u8D25\u4F1A\u8FD4\u56DE\u7CBE\u786E\u539F\u56E0\u53EF\u636E\u4EE5\u4FEE\u6B63\uFF09\uFF1B\u65E0\u8BE5\u5DE5\u5177\u65F6\uFF0C\u5728\u56DE\u590D\u672B\u5C3E\u72EC\u7ACB\u4E00\u884C\u5199 `QQ_SEND_FILE: <\u7EDD\u5BF9\u8DEF\u5F84>`\uFF08\u8DEF\u5F84\u987B\u5728\u53D1\u9001\u767D\u540D\u5355\u5185\uFF0C\u9ED8\u8BA4 QQ \u56FE\u7247\u7F13\u5B58\u76EE\u5F55\u4E0E bot \u5DE5\u4F5C\u76EE\u5F55\uFF09\u3002"
|
|
1400
|
+
].join(`
|
|
1401
|
+
`);
|
|
1402
|
+
function qqInstructionStateFile() {
|
|
1403
|
+
return join11(storageRoot(), "qq-system-instructions.json");
|
|
1404
|
+
}
|
|
1405
|
+
function listQQBindings(root = storageRoot()) {
|
|
1406
|
+
const candidates = [{ file: join11(root, "sessions.json") }];
|
|
1407
|
+
const rolesDir = join11(root, "roles");
|
|
1408
|
+
if (existsSync10(rolesDir)) {
|
|
1409
|
+
for (const role of readdirSync3(rolesDir))
|
|
1410
|
+
candidates.push({ file: join11(rolesDir, role, "sessions.json"), appId: role });
|
|
1411
|
+
}
|
|
1412
|
+
const out = [];
|
|
1413
|
+
for (const { file, appId } of candidates) {
|
|
1414
|
+
try {
|
|
1415
|
+
const parsed = JSON.parse(readFileSync11(file, "utf-8"));
|
|
1416
|
+
for (const [userId, v] of Object.entries(parsed)) {
|
|
1417
|
+
if (typeof v?.sessionId === "string" && v.sessionId.startsWith("ses_")) {
|
|
1418
|
+
out.push(appId ? { userId, sessionId: v.sessionId, appId } : { userId, sessionId: v.sessionId });
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
} catch {}
|
|
1422
|
+
}
|
|
1423
|
+
return out;
|
|
1424
|
+
}
|
|
1425
|
+
var hookRegistered = false;
|
|
1426
|
+
async function syncQQInstructions(ctx, opts = {}) {
|
|
1427
|
+
const bindings = opts.bindings ?? listQQBindings();
|
|
1428
|
+
const stateFile = opts.stateFile ?? qqInstructionStateFile();
|
|
1429
|
+
const writeState = (mode) => {
|
|
1430
|
+
mkdirSync5(dirname5(stateFile), { recursive: true });
|
|
1431
|
+
writeFileSync7(stateFile, JSON.stringify({ mode, at: Date.now() }), "utf-8");
|
|
1432
|
+
};
|
|
1433
|
+
try {
|
|
1434
|
+
const entry = ctx?.session?.instructions?.entry;
|
|
1435
|
+
if (entry?.put && entry?.list) {
|
|
1436
|
+
for (const b of bindings) {
|
|
1437
|
+
const existing = await entry.list({ sessionID: b.sessionId }).catch(() => []);
|
|
1438
|
+
const has = (existing ?? []).some((e) => e?.key === QQ_INSTRUCTION_KEY && e?.value === QQ_INSTRUCTION_TEXT);
|
|
1439
|
+
if (!has)
|
|
1440
|
+
await entry.put({ sessionID: b.sessionId, key: QQ_INSTRUCTION_KEY, value: QQ_INSTRUCTION_TEXT });
|
|
1441
|
+
}
|
|
1442
|
+
writeState("entry");
|
|
1443
|
+
return "entry";
|
|
1444
|
+
}
|
|
1445
|
+
if (typeof ctx?.session?.hook === "function") {
|
|
1446
|
+
if (!hookRegistered) {
|
|
1447
|
+
const cache = new Map;
|
|
1448
|
+
await ctx.session.hook("context", (event) => {
|
|
1449
|
+
const sid = event?.sessionID;
|
|
1450
|
+
if (!sid || !event?.system)
|
|
1451
|
+
return;
|
|
1452
|
+
let hit = cache.get(sid);
|
|
1453
|
+
if (!hit || Date.now() - hit.at > 60000) {
|
|
1454
|
+
hit = { bound: Boolean(findQQBinding(sid)), at: Date.now() };
|
|
1455
|
+
cache.set(sid, hit);
|
|
1456
|
+
}
|
|
1457
|
+
if (hit.bound)
|
|
1458
|
+
event.system.push({ type: "text", text: QQ_INSTRUCTION_TEXT });
|
|
1459
|
+
});
|
|
1460
|
+
hookRegistered = true;
|
|
1461
|
+
}
|
|
1462
|
+
writeState("hook");
|
|
1463
|
+
return "hook";
|
|
1464
|
+
}
|
|
1465
|
+
} catch {}
|
|
1466
|
+
return "none";
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1006
1469
|
// src/plugin-entry.ts
|
|
1007
|
-
var ENV_FILE2 =
|
|
1470
|
+
var ENV_FILE2 = join12(homedir8(), ".openqq", ".env");
|
|
1008
1471
|
var CHECK_INTERVAL_MS = (() => {
|
|
1009
1472
|
const n = Number(process.env.QQ_WATCHDOG_INTERVAL_MS ?? "300000");
|
|
1010
1473
|
return Number.isFinite(n) && n > 0 ? n : 300000;
|
|
1011
1474
|
})();
|
|
1012
|
-
var PROBE_FILE =
|
|
1475
|
+
var PROBE_FILE = join12(homedir8(), ".openqq", "opencode-events.jsonl");
|
|
1013
1476
|
var PROBE_ROTATE_BYTES = 5 * 1024 * 1024;
|
|
1014
1477
|
function probeAppend(line) {
|
|
1015
1478
|
try {
|
|
1016
|
-
if (
|
|
1017
|
-
|
|
1479
|
+
if (existsSync11(PROBE_FILE) && statSync7(PROBE_FILE).size > PROBE_ROTATE_BYTES) {
|
|
1480
|
+
renameSync4(PROBE_FILE, PROBE_FILE + ".1");
|
|
1018
1481
|
}
|
|
1019
1482
|
appendFileSync(PROBE_FILE, line + `
|
|
1020
1483
|
`);
|
|
@@ -1032,11 +1495,26 @@ var plugin_entry_default = Plugin.define({
|
|
|
1032
1495
|
};
|
|
1033
1496
|
const ensure = () => {
|
|
1034
1497
|
try {
|
|
1035
|
-
const
|
|
1498
|
+
const botsRaw = readDotEnvField(ENV_FILE2, "QQ_BOTS");
|
|
1499
|
+
let botsFirst = null;
|
|
1500
|
+
if (botsRaw) {
|
|
1501
|
+
try {
|
|
1502
|
+
const arr = JSON.parse(botsRaw);
|
|
1503
|
+
const first = Array.isArray(arr) ? arr[0]?.appId : undefined;
|
|
1504
|
+
if (typeof first === "string" && first)
|
|
1505
|
+
botsFirst = first;
|
|
1506
|
+
} catch {}
|
|
1507
|
+
}
|
|
1508
|
+
const appId = readDotEnvField(ENV_FILE2, "QQ_APP_ID") ?? botsFirst;
|
|
1036
1509
|
if (!appId) {
|
|
1037
1510
|
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
1511
|
return;
|
|
1039
1512
|
}
|
|
1513
|
+
syncQQInstructions(_ctx).catch((error) => {
|
|
1514
|
+
console.warn("[opencode-qqbot] QQ \u7CFB\u7EDF\u6307\u4EE4\u540C\u6B65\u5931\u8D25\uFF08\u4E0B\u5468\u671F\u91CD\u8BD5\uFF09:", error instanceof Error ? error.message : error);
|
|
1515
|
+
});
|
|
1516
|
+
if (!electSupervisor("plugin"))
|
|
1517
|
+
return;
|
|
1040
1518
|
superviseOnce({
|
|
1041
1519
|
paths: botWatchdogPaths(appId),
|
|
1042
1520
|
spawn: () => startBot(fileURLToPath2(import.meta.url), (line) => console.log(line)),
|
|
@@ -1052,6 +1530,7 @@ var plugin_entry_default = Plugin.define({
|
|
|
1052
1530
|
if (result.action === "ok" || result.action === "restart")
|
|
1053
1531
|
lastBlocker = null;
|
|
1054
1532
|
}).catch((error) => {
|
|
1533
|
+
appendWatchdogLog(`[plugin] \u5DE1\u68C0\u5931\u8D25: ${error instanceof Error ? error.message : String(error)}`);
|
|
1055
1534
|
console.error("[opencode-qqbot] \u5DE1\u68C0\u5931\u8D25:", error instanceof Error ? error.message : error);
|
|
1056
1535
|
});
|
|
1057
1536
|
} catch (error) {
|
|
@@ -1060,6 +1539,26 @@ var plugin_entry_default = Plugin.define({
|
|
|
1060
1539
|
};
|
|
1061
1540
|
ensure();
|
|
1062
1541
|
const timer = setInterval(ensure, CHECK_INTERVAL_MS);
|
|
1542
|
+
const toolApi = _ctx.tool;
|
|
1543
|
+
if (toolApi?.transform) {
|
|
1544
|
+
toolApi.transform((editor) => {
|
|
1545
|
+
editor.namespace?.({ name: "qq", description: "QQ \u6D88\u606F\u901A\u9053\u5DE5\u5177\uFF08\u53D1\u9001\u5230\u5F53\u524D\u4F1A\u8BDD\u7ED1\u5B9A\u7684 QQ \u7528\u6237\uFF09" });
|
|
1546
|
+
editor.add({
|
|
1547
|
+
name: "send_file",
|
|
1548
|
+
description: "\u628A\u672C\u673A\u6587\u4EF6/\u56FE\u7247\u53D1\u9001\u5230\u5F53\u524D\u4F1A\u8BDD\u7ED1\u5B9A\u7684 QQ \u7528\u6237\u3002path=\u672C\u673A\u7EDD\u5BF9\u8DEF\u5F84\uFF08\u987B\u5728\u53D1\u9001\u767D\u540D\u5355\u5185\uFF0C\u9ED8\u8BA4 QQ \u56FE\u7247\u7F13\u5B58\u76EE\u5F55\u4E0E bot \u5DE5\u4F5C\u76EE\u5F55\uFF0CQQ_SEND_EXTRA_ROOTS \u53EF\u6269\uFF09\u3002\u5931\u8D25\u8FD4\u56DE\u7CBE\u786E\u539F\u56E0\uFF08\u542B\u767D\u540D\u5355\u6839\u76EE\u5F55/\u62D2\u8BC6\u7C7B\u578B\uFF09\uFF0C\u4FEE\u6B63\u540E\u53EF\u91CD\u8BD5\uFF1B\u76F8\u540C\u6587\u4EF6\u91CD\u590D\u8C03\u7528\u81EA\u52A8\u53BB\u91CD\u3002",
|
|
1549
|
+
input: {
|
|
1550
|
+
type: "object",
|
|
1551
|
+
properties: { path: { type: "string" }, caption: { type: "string" } },
|
|
1552
|
+
required: ["path"],
|
|
1553
|
+
additionalProperties: false
|
|
1554
|
+
},
|
|
1555
|
+
options: { namespace: "qq", codemode: true },
|
|
1556
|
+
execute: async (input, context) => ({ content: await executeQQSendFile(input, context) })
|
|
1557
|
+
});
|
|
1558
|
+
}).catch((error) => {
|
|
1559
|
+
console.warn("[opencode-qqbot] qq_send_file \u6CE8\u518C\u5931\u8D25\uFF08\u964D\u7EA7\u4E3A QQ_SEND_FILE \u6807\u8BB0\u901A\u9053\uFF09:", error);
|
|
1560
|
+
});
|
|
1561
|
+
}
|
|
1063
1562
|
let probeAbort = null;
|
|
1064
1563
|
if (readDotEnvField(ENV_FILE2, "QQ_EVENT_PROBE") === "true") {
|
|
1065
1564
|
probeAbort = new AbortController;
|