qq-bot-roost 1.0.11 → 1.0.12
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 +2 -2
- package/package.json +2 -2
- package/src/bot.js +12 -0
- package/src/config.js +6 -0
- package/src/message.js +2 -0
- package/src/outbound.js +39 -0
- package/src/plugin/loader.js +42 -10
- package/src/plugin/runtime-errors.js +27 -0
- package/src/plugin/snapshot.js +64 -0
- package/src/runtime.js +18 -0
- package/src/web/server.js +32 -1
- package/web/app.js +42 -1
- package/web/index.html +3 -0
package/README.md
CHANGED
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
|
|
9
9
|
<img src="https://img.shields.io/badge/Node.js-22.13%2B-339933?logo=node.js&logoColor=white" alt="Node.js 22.13+">
|
|
10
10
|
<img src="https://img.shields.io/badge/dependencies-0-brightgreen" alt="零依赖">
|
|
11
|
-
<img src="https://img.shields.io/badge/tests-
|
|
11
|
+
<img src="https://img.shields.io/badge/tests-902%20passed-brightgreen" alt="测试 902 项">
|
|
12
12
|
<img src="https://img.shields.io/badge/plugins-JS%20%7C%20Python%20%7C%20Go%20%7C%20any-blue" alt="多语言插件">
|
|
13
|
-
<img src="https://img.shields.io/badge/version-1.0.
|
|
13
|
+
<img src="https://img.shields.io/badge/version-1.0.12-blueviolet" alt="版本 1.0.12">
|
|
14
14
|
<img src="https://img.shields.io/badge/license-AGPL--3.0--only-blue" alt="AGPL-3.0-only">
|
|
15
15
|
<a href="https://github.com/tdcq9594/qq-bot-roost/actions"><img src="https://img.shields.io/github/actions/workflow/status/tdcq9594/qq-bot-roost/ci.yml?branch=master" alt="CI"></a>
|
|
16
16
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "qq-bot-roost",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.12",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "栖 Roost:零依赖的 QQ 官方机器人框架,填 AppID/AppSecret 即连,插件可写任意语言",
|
|
6
6
|
"license": "AGPL-3.0-only",
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"start": "node src/main.js",
|
|
30
30
|
"mock": "node src/main.js --mock",
|
|
31
31
|
"check": "node src/main.js --check",
|
|
32
|
-
"test": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/reply-auto.mjs",
|
|
32
|
+
"test": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/reply-auto.mjs && node --test test/plugin-observability.mjs && node --test test/outbound-dry.mjs",
|
|
33
33
|
"test:e2e": "node test/e2e.mjs",
|
|
34
34
|
"test:all": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/reply-auto.mjs && node test/e2e.mjs && node test/live-driver.mjs",
|
|
35
35
|
"check:secrets": "node scripts/check-secrets.mjs",
|
package/src/bot.js
CHANGED
|
@@ -813,6 +813,11 @@ export class BotRuntime {
|
|
|
813
813
|
bot: this,
|
|
814
814
|
});
|
|
815
815
|
} catch (e) {
|
|
816
|
+
/** 事件监听器也算运行期错误;以前只有消息 listener 留痕,这里会静默丢。
|
|
817
|
+
* 发送侧的已知限制不是插件写错,别刷运行期错误卡。 */
|
|
818
|
+
if (!['offline', 'expired', 'quota', 'rate'].includes(e?.code)) {
|
|
819
|
+
this.plugins?.noteRuntimeError?.(l.pluginId, e);
|
|
820
|
+
}
|
|
816
821
|
this.metrics.bump('errors');
|
|
817
822
|
this.log.error(`监听器 ${l.pluginId} 处理 ${eventName} 出错:`, e.stack || e.message);
|
|
818
823
|
}
|
|
@@ -1005,6 +1010,8 @@ export class BotRuntime {
|
|
|
1005
1010
|
this.log.warn(`命令 ${commandEntry.name} 回复失败: ${e.message}`);
|
|
1006
1011
|
return;
|
|
1007
1012
|
}
|
|
1013
|
+
/** 命令 handler 抛错也要在面板留痕(已知发送限制不记,免得刷屏) */
|
|
1014
|
+
this.plugins?.noteRuntimeError?.(commandEntry.pluginId, e);
|
|
1008
1015
|
this.log.error(
|
|
1009
1016
|
`命令 ${commandEntry.name}(插件 ${commandEntry.pluginId})执行出错:`,
|
|
1010
1017
|
e.stack || e.message,
|
|
@@ -1060,6 +1067,11 @@ export class BotRuntime {
|
|
|
1060
1067
|
if (ret === true) msg.claim();
|
|
1061
1068
|
if (ret === true || msg.replied) handled = true;
|
|
1062
1069
|
} catch (e) {
|
|
1070
|
+
// 运行期错误也要留痕:以前只进日志,面板上看不出插件在反复抛错。
|
|
1071
|
+
// 发送侧的已知限制不算插件异常,跟命令 handler 保持同一口径。
|
|
1072
|
+
if (!['offline', 'expired', 'quota', 'rate'].includes(e?.code)) {
|
|
1073
|
+
this.plugins?.noteRuntimeError?.(l.pluginId, e);
|
|
1074
|
+
}
|
|
1063
1075
|
this.metrics.bump('errors');
|
|
1064
1076
|
this.log.error(`监听器 ${l.pluginId} 处理 ${evt} 出错:`, e.stack || e.message);
|
|
1065
1077
|
}
|
package/src/config.js
CHANGED
|
@@ -234,6 +234,12 @@ const BOT_DEFAULTS = {
|
|
|
234
234
|
dailyActive: 1000,
|
|
235
235
|
activePerMinute: 20,
|
|
236
236
|
downgradeToActive: true,
|
|
237
|
+
/**
|
|
238
|
+
* E3:dry 出站截获。开着时**不真发**,只记下「本来会发什么」,
|
|
239
|
+
* 面板「概览」页可以看最近 50 条。默认关。
|
|
240
|
+
* 只能截到**本进程内建插件**的出站;外部子进程插件(NDJSON)不经过这里。
|
|
241
|
+
*/
|
|
242
|
+
dryRun: false,
|
|
237
243
|
},
|
|
238
244
|
|
|
239
245
|
session: {
|
package/src/message.js
CHANGED
|
@@ -1061,6 +1061,8 @@ export function buildMessage(eventName, d, { api, cfg, outbound, session, traceI
|
|
|
1061
1061
|
return await send({ ...payload, ...(rid ? { requestId: rid } : {}) }, true);
|
|
1062
1062
|
} catch (e) {
|
|
1063
1063
|
log.error(`replyAuto 发送失败(${plan.mode}):`, e.message);
|
|
1064
|
+
/** 失败也要给诊断回调一个终态:只返回 null,调用方分不清「空内容」和「没发出去」 */
|
|
1065
|
+
report({ mode: plan.mode, ok: false, reason: 'send-failed', error: e.message });
|
|
1064
1066
|
return null;
|
|
1065
1067
|
}
|
|
1066
1068
|
}
|
package/src/outbound.js
CHANGED
|
@@ -293,6 +293,13 @@ export class Outbound {
|
|
|
293
293
|
this.dailyActive = Math.max(0, o.dailyActive ?? 1000);
|
|
294
294
|
this.activePerMin = Math.max(0, o.activePerMinute ?? 20);
|
|
295
295
|
this.downgrade = o.downgradeToActive !== false;
|
|
296
|
+
/**
|
|
297
|
+
* E3:dry 出站截获。开着时 `send()` 不真发,只记下本来会发什么。
|
|
298
|
+
* **只能截本进程内建插件的出站**:外部子进程插件走 NDJSON,不经过这里。
|
|
299
|
+
*/
|
|
300
|
+
this.dry = Boolean(o.dryRun);
|
|
301
|
+
/** 最近 50 条「本来会发出去」的消息,面板只读展示 */
|
|
302
|
+
this.dryLog = [];
|
|
296
303
|
|
|
297
304
|
/** msgId -> 已用被动回复次数。官方:同一条消息最多 5 次 */
|
|
298
305
|
this.passiveCount = new Map();
|
|
@@ -317,6 +324,36 @@ export class Outbound {
|
|
|
317
324
|
};
|
|
318
325
|
}
|
|
319
326
|
|
|
327
|
+
/* ---------------- E3:dry 出站截获 ---------------- */
|
|
328
|
+
|
|
329
|
+
/** 面板开关。返回切换后的状态 */
|
|
330
|
+
setDry(on) {
|
|
331
|
+
this.dry = on === true;
|
|
332
|
+
if (!this.dry) this.dryLog.length = 0;
|
|
333
|
+
return this.dry;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
#drySend(opts) {
|
|
337
|
+
const p = opts?.payload ?? {};
|
|
338
|
+
const text = String(p.markdown?.content ?? p.content ?? '');
|
|
339
|
+
const row = {
|
|
340
|
+
at: Date.now(),
|
|
341
|
+
kind: String(opts?.kind || ''),
|
|
342
|
+
target: String(opts?.target || ''),
|
|
343
|
+
/** 有 msgId / receivedAt 就是被动回复,否则是主动推送 */
|
|
344
|
+
passive: Boolean(p.msgId || opts?.receivedAt),
|
|
345
|
+
text: text.slice(0, 200),
|
|
346
|
+
files: Array.isArray(p.files) ? p.files.length : 0,
|
|
347
|
+
keyboard: Boolean(p.keyboard),
|
|
348
|
+
};
|
|
349
|
+
this.dryLog.push(row);
|
|
350
|
+
if (this.dryLog.length > 50) this.dryLog.shift();
|
|
351
|
+
this.stats.dry = (this.stats.dry || 0) + 1;
|
|
352
|
+
log.info(`[dry] ${row.kind} ${row.target}:${row.text.slice(0, 40)}`);
|
|
353
|
+
/** 形状和真实发送一致,调用方不用分叉;`dry:true` 让它知道没真发 */
|
|
354
|
+
return { ok: true, dry: true, id: '', pending: false };
|
|
355
|
+
}
|
|
356
|
+
|
|
320
357
|
/* ---------------- 对外主入口 ---------------- */
|
|
321
358
|
|
|
322
359
|
/**
|
|
@@ -340,6 +377,8 @@ export class Outbound {
|
|
|
340
377
|
* 账本是**增强**不是主链路:`claim` 失败一律退回「照发」,不能让记账把消息堵死。
|
|
341
378
|
*/
|
|
342
379
|
async send(opts) {
|
|
380
|
+
/** E3:dry 模式在**最顶层**截住,连投递账本和限速都不进——它本来就没发 */
|
|
381
|
+
if (this.dry) return this.#drySend(opts);
|
|
343
382
|
const requestId = String(opts?.requestId ?? '').trim();
|
|
344
383
|
if (!requestId || !this.delivery) {
|
|
345
384
|
/**
|
package/src/plugin/loader.js
CHANGED
|
@@ -14,6 +14,8 @@ import { satisfies, frameworkVersion } from '../semver.js';
|
|
|
14
14
|
import { PageRegistry } from './pages.js';
|
|
15
15
|
import { RouteRegistry } from './routes.js';
|
|
16
16
|
import { Declarations, normalizeManifest, checkEngines } from './manifest.js';
|
|
17
|
+
import { pushRuntimeError } from './runtime-errors.js';
|
|
18
|
+
import { makeSnapshot, pruneSnapshots } from './snapshot.js';
|
|
17
19
|
|
|
18
20
|
const log = createLogger('plugins');
|
|
19
21
|
|
|
@@ -73,6 +75,12 @@ export class PluginManager {
|
|
|
73
75
|
* 完全看不出是哪一行,插件作者只能靠猜。面板上展开就能看到调用栈。
|
|
74
76
|
*/
|
|
75
77
|
this.errorStacks = new Map();
|
|
78
|
+
/**
|
|
79
|
+
* id -> 最近 8 条**运行期**错误。
|
|
80
|
+
* 加载期错误看 errorStacks;这里是「装得上、面板显示成功,但 handler 每轮抛错」,
|
|
81
|
+
* 以前一点痕迹都没有,用户只看到机器人不回话。
|
|
82
|
+
*/
|
|
83
|
+
this.runtimeErrors = new Map();
|
|
76
84
|
/**
|
|
77
85
|
* id -> 插件自己的内存状态对象。
|
|
78
86
|
*
|
|
@@ -336,12 +344,11 @@ export class PluginManager {
|
|
|
336
344
|
/**
|
|
337
345
|
* 「热重载只对入口生效」是个容易踩的坑,报错里点名说清楚。
|
|
338
346
|
*
|
|
339
|
-
*
|
|
340
|
-
*
|
|
341
|
-
*
|
|
342
|
-
* `
|
|
343
|
-
*
|
|
344
|
-
* ESM 没有清缓存的 API,所以只能提示重启——但至少要让人知道为什么。
|
|
347
|
+
* 历史坑:早年只给 `index.js` 加 `?t=`,子模块(`outbound.js` 之类)
|
|
348
|
+
* 还在 Node 的模块缓存里,改了子模块再重载就成了「新入口 + 旧子模块」,
|
|
349
|
+
* 表现为 `does not provide an export named 'xxx'`。
|
|
350
|
+
* 现在 `#loadInternal` 用快照法整目录换路径加载,这个坑已消;
|
|
351
|
+
* 这条提示留作其他原因导致同名报错时的解释。
|
|
345
352
|
*/
|
|
346
353
|
const msg = String(e?.message ?? '');
|
|
347
354
|
if (/does not provide an export named/.test(msg)) {
|
|
@@ -416,9 +423,15 @@ export class PluginManager {
|
|
|
416
423
|
});
|
|
417
424
|
}
|
|
418
425
|
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
426
|
+
/**
|
|
427
|
+
* 快照法热重载:整目录复制到 `.roost-cache/<stamp>/` 再 import。
|
|
428
|
+
* ESM 按路径缓存,只给入口加 `?t=` 重不了子模块;换整条路径才会连带重载。
|
|
429
|
+
* 外部插件走 `#loadExternal`,stop/start 本来就是干净重载,不需要这一步。
|
|
430
|
+
* 先清旧快照再 import:即使这次 import 失败,下次也不会越积越多。
|
|
431
|
+
*/
|
|
432
|
+
const snap = await makeSnapshot(dir, entryFile);
|
|
433
|
+
await pruneSnapshots(snap.snapRoot, snap.stamp);
|
|
434
|
+
const mod = await import(pathToFileURL(snap.entry).href);
|
|
422
435
|
const meta = mod.default ?? mod.plugin;
|
|
423
436
|
if (!meta || typeof meta.setup !== 'function') {
|
|
424
437
|
throw new Error('默认导出必须是 { id, setup(ctx) } 形式的对象');
|
|
@@ -674,8 +687,18 @@ export class PluginManager {
|
|
|
674
687
|
return true;
|
|
675
688
|
}
|
|
676
689
|
|
|
690
|
+
/** 记一条插件 handler 的运行期异常(环形 8 条,面板可见)。 */
|
|
691
|
+
noteRuntimeError(id, err) {
|
|
692
|
+
if (!id) return;
|
|
693
|
+
const ring = this.runtimeErrors.get(id) ?? [];
|
|
694
|
+
pushRuntimeError(ring, err);
|
|
695
|
+
this.runtimeErrors.set(id, ring);
|
|
696
|
+
}
|
|
697
|
+
|
|
677
698
|
async reload(id) {
|
|
678
699
|
await this.unload(id);
|
|
700
|
+
/** 新实例是干净的:旧 handler 抛过的错别留在面板上冒充「还在报错」 */
|
|
701
|
+
this.runtimeErrors.delete(id);
|
|
679
702
|
return this.load(id);
|
|
680
703
|
}
|
|
681
704
|
|
|
@@ -695,6 +718,7 @@ export class PluginManager {
|
|
|
695
718
|
}
|
|
696
719
|
this.errors.delete(id);
|
|
697
720
|
this.errorStacks.delete(id);
|
|
721
|
+
this.runtimeErrors.delete(id);
|
|
698
722
|
this.stateStore.delete(id);
|
|
699
723
|
this.meta.delete(id);
|
|
700
724
|
this.diskIds.delete(id);
|
|
@@ -704,7 +728,14 @@ export class PluginManager {
|
|
|
704
728
|
async setEnabled(id, enabled) {
|
|
705
729
|
this.state[id] = enabled;
|
|
706
730
|
await this.#writeState();
|
|
707
|
-
if (enabled)
|
|
731
|
+
if (enabled) {
|
|
732
|
+
/**
|
|
733
|
+
* 已经加载的插件再点「启用」不能二次 load:会重复注册路由并抛错,
|
|
734
|
+
* load() 的 catch 反而把 loaded/routes 清掉,插件被自己卸了(审查实测 1→0)。
|
|
735
|
+
*/
|
|
736
|
+
if (this.loaded.has(id)) return true;
|
|
737
|
+
return this.load(id);
|
|
738
|
+
}
|
|
708
739
|
return this.unload(id);
|
|
709
740
|
}
|
|
710
741
|
|
|
@@ -1015,6 +1046,7 @@ export class PluginManager {
|
|
|
1015
1046
|
menuMissing: Boolean(item?.menuMissing),
|
|
1016
1047
|
error: this.errors.get(id) ?? ext?.error ?? '',
|
|
1017
1048
|
errorStack: this.errorStacks.get(id) ?? '',
|
|
1049
|
+
runtimeErrors: (this.runtimeErrors.get(id) ?? []).slice(),
|
|
1018
1050
|
};
|
|
1019
1051
|
});
|
|
1020
1052
|
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 插件**运行期**错误的环形缓冲。
|
|
3
|
+
*
|
|
4
|
+
* 加载期错误一直有 `errorStacks`;但「装得上、面板显示成功、handler 每轮抛错」
|
|
5
|
+
* 以前一点痕迹都没有,用户只看到机器人不回话。留最近 8 条就够看出
|
|
6
|
+
* 「一直在报同一个错」,又不会把内存吃穿。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export const RUNTIME_ERROR_MAX = 8;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @param {Array} ring 已有条目(原地追加后返回同一个数组)
|
|
13
|
+
* @param {unknown} err 异常对象或字符串
|
|
14
|
+
* @param {number} [at] 时间戳,测试里可注入
|
|
15
|
+
* @returns {Array} 截断到 8 条的环形缓冲
|
|
16
|
+
*/
|
|
17
|
+
export function pushRuntimeError(ring, err, at = Date.now()) {
|
|
18
|
+
const list = Array.isArray(ring) ? ring : [];
|
|
19
|
+
list.push({
|
|
20
|
+
at,
|
|
21
|
+
message: String(err?.message ?? err ?? ''),
|
|
22
|
+
// 完整堆栈太长,面板只展得开前几行;第一行通常就够定位
|
|
23
|
+
stack: String(err?.stack ?? '').split('\n').slice(0, 4).join('\n'),
|
|
24
|
+
});
|
|
25
|
+
if (list.length > RUNTIME_ERROR_MAX) list.splice(0, list.length - RUNTIME_ERROR_MAX);
|
|
26
|
+
return list;
|
|
27
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
/** 插件目录里不该进快照的**一级**子目录。 */
|
|
5
|
+
const SKIP_TOP = new Set(['node_modules', '.roost-cache', 'data', 'logs', 'config', '.git']);
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* 自己遍历复制,不用 `fs.cp`:快照在插件目录**内部**,而 fs.cp 会在开复制前
|
|
9
|
+
* 直接拒绝「目标是源的子目录」(ERR_FS_CP_EINVAL),哪怕 filter 排除了它。
|
|
10
|
+
* 排除只在**插件根目录那一层**生效:嵌套的 `src/data`、`lib/config` 是插件
|
|
11
|
+
* 自己的代码/资源,不该被一并丢掉(审查实测 S11/S12)。
|
|
12
|
+
*/
|
|
13
|
+
async function copyTree(srcDir, destDir, top = false) {
|
|
14
|
+
await fs.mkdir(destDir, { recursive: true });
|
|
15
|
+
for (const e of await fs.readdir(srcDir, { withFileTypes: true })) {
|
|
16
|
+
if (top && SKIP_TOP.has(e.name)) continue;
|
|
17
|
+
const from = path.join(srcDir, e.name);
|
|
18
|
+
const to = path.join(destDir, e.name);
|
|
19
|
+
if (e.isDirectory()) await copyTree(from, to, false);
|
|
20
|
+
else if (e.isFile()) await fs.copyFile(from, to);
|
|
21
|
+
else if (e.isSymbolicLink()) {
|
|
22
|
+
/**
|
|
23
|
+
* symlink 原先被静默漏掉。指向普通文件时按目标内容复制成快照里的真文件;
|
|
24
|
+
* 指向目录的链接不跟随(避免成环),插件不该靠这种结构装代码。
|
|
25
|
+
*/
|
|
26
|
+
const real = await fs.realpath(from).catch(() => null);
|
|
27
|
+
const st = real ? await fs.stat(real).catch(() => null) : null;
|
|
28
|
+
if (st?.isFile()) await fs.copyFile(real, to).catch(() => {});
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 把内建插件复制成一份带唯一戳的快照,返回快照入口路径。
|
|
35
|
+
*
|
|
36
|
+
* 为什么不再用 `?t=`:ESM 按**路径**缓存,入口加查询参数只会重加载入口,
|
|
37
|
+
* 它 import 的子模块还留在旧缓存里——典型表现是「改了 outbound.js,重载后
|
|
38
|
+
* 报 does not provide an export named xxx」,只能重启进程。整目录换路径,
|
|
39
|
+
* 入口和所有相对 import 的子模块才会一起重载。
|
|
40
|
+
*
|
|
41
|
+
* 快照放在**插件目录内部**(`.roost-cache/<stamp>/`):这样插件 `import '某个 npm 包'`
|
|
42
|
+
* 时,Node 向上查找能落到插件自己的 `node_modules`;复制时把依赖、数据目录、
|
|
43
|
+
* 旧快照都排除掉,避免每次重载把目录越滚越大。
|
|
44
|
+
*
|
|
45
|
+
* @returns {Promise<{snapRoot:string, snapDir:string, stamp:string, entry:string}>}
|
|
46
|
+
*/
|
|
47
|
+
export async function makeSnapshot(dir, entryFile) {
|
|
48
|
+
const snapRoot = path.join(dir, '.roost-cache');
|
|
49
|
+
const stamp = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
50
|
+
const snapDir = path.join(snapRoot, stamp);
|
|
51
|
+
await fs.mkdir(snapRoot, { recursive: true });
|
|
52
|
+
await copyTree(dir, snapDir, true);
|
|
53
|
+
return { snapRoot, snapDir, stamp, entry: path.join(snapDir, path.basename(entryFile)) };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 只留当前这一份快照。旧的不删会随每次重载线性增长。 */
|
|
57
|
+
export async function pruneSnapshots(snapRoot, keepStamp) {
|
|
58
|
+
const entries = await fs.readdir(snapRoot).catch(() => []);
|
|
59
|
+
await Promise.all(
|
|
60
|
+
entries
|
|
61
|
+
.filter((x) => x !== keepStamp)
|
|
62
|
+
.map((x) => fs.rm(path.join(snapRoot, x), { recursive: true, force: true }).catch(() => {})),
|
|
63
|
+
);
|
|
64
|
+
}
|
package/src/runtime.js
CHANGED
|
@@ -6,6 +6,20 @@
|
|
|
6
6
|
*/
|
|
7
7
|
export const SENSITIVE_KEY = /^(auth_token|token|access_token|secret|client_secret|cookie|password)$/i;
|
|
8
8
|
|
|
9
|
+
/**
|
|
10
|
+
* 文本级脱敏。抽出来给面板 `/api/plugins` 下发错误栈用:handler 抛出的
|
|
11
|
+
* `Error.stack` 里可能带请求 URL / token,原样回浏览器会泄密。
|
|
12
|
+
* 事件报文仍走下面的 `redact()`(对象递归),这里只管一段文本。
|
|
13
|
+
*/
|
|
14
|
+
export function redactText(value) {
|
|
15
|
+
return String(value ?? '')
|
|
16
|
+
.replace(/auth_token=[^&"\s]*/g, 'auth_token=***')
|
|
17
|
+
.replace(/msg_idx=[^&"\s]*/g, 'msg_idx=***')
|
|
18
|
+
.replace(/(Authorization["']?\s*[:=]\s*["']?)(?:Bearer\s+)?[A-Za-z0-9._~+/=-]{8,}/gi, '$1***')
|
|
19
|
+
.replace(/((?:token|access_token|password|secret|api[_-]?key|cookie)["']?\s*[:=]\s*["']?)([^\s"',;&]{4,})/gi, '$1***')
|
|
20
|
+
.slice(0, 400);
|
|
21
|
+
}
|
|
22
|
+
|
|
9
23
|
/**
|
|
10
24
|
* 事件报文脱敏。
|
|
11
25
|
* 群消息的 message_scene.ext 里带 auth_token,属于敏感凭证,
|
|
@@ -27,6 +41,10 @@ function redact(value, depth = 0) {
|
|
|
27
41
|
}
|
|
28
42
|
return out;
|
|
29
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* 事件报文沿用原来的窄规则,**不调用 redactText**:那会把 token=/Authorization
|
|
46
|
+
* 也抹掉、改变既有 sanitizePayload 输出。面板错误栈才走 redactText(见 server.js)。
|
|
47
|
+
*/
|
|
30
48
|
if (typeof value === 'string') {
|
|
31
49
|
return value
|
|
32
50
|
.replace(/auth_token=[^&"\s]*/g, 'auth_token=***')
|
package/src/web/server.js
CHANGED
|
@@ -4,6 +4,7 @@ import fsSync from 'node:fs';
|
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import crypto from 'node:crypto';
|
|
6
6
|
import { ROOT } from '../config.js';
|
|
7
|
+
import { redactText } from '../runtime.js';
|
|
7
8
|
import { DIRS, botPaths, listBotIds, rel } from '../paths.js';
|
|
8
9
|
import { createLogger, recentLogs, onLog, getLevel, setLevel } from '../logger.js';
|
|
9
10
|
import { EVENT_NAMES, INTENT_META, describeIntents, groupEvents } from '../events.js';
|
|
@@ -576,6 +577,14 @@ async function startWebServerInstance({
|
|
|
576
577
|
* 面板上只显示截断的 openid,用户认不出是哪个群、哪个人。
|
|
577
578
|
* 群名从 rt.groupNames 拿(异步拉的缓存),私聊对象从 recentPeople 拿。
|
|
578
579
|
*/
|
|
580
|
+
/**
|
|
581
|
+
* E3:dry 出站截获状态 + 最近 20 条(只读)。
|
|
582
|
+
* 只能截**本进程内建插件**的出站;外部子进程插件走 NDJSON,不经过 outbound。
|
|
583
|
+
*/
|
|
584
|
+
snap.dry = rt?.outbound
|
|
585
|
+
? { on: Boolean(rt.outbound.dry), recent: (rt.outbound.dryLog ?? []).slice(-20) }
|
|
586
|
+
: null;
|
|
587
|
+
|
|
579
588
|
if (Array.isArray(snap.chats)) {
|
|
580
589
|
const people = rt?.listRecentPeople?.(200) ?? [];
|
|
581
590
|
snap.chats = snap.chats.map((c) => ({
|
|
@@ -1473,6 +1482,14 @@ async function startWebServerInstance({
|
|
|
1473
1482
|
return json(res, 200, statusPayload(rt));
|
|
1474
1483
|
}
|
|
1475
1484
|
|
|
1485
|
+
/** E3:dry 出站截获开关(只影响本进程内建插件;不落盘,重启回默认) */
|
|
1486
|
+
if (pathname === '/api/dry' && req.method === 'POST') {
|
|
1487
|
+
const body = await readBody(req);
|
|
1488
|
+
if (!rt?.outbound) return json(res, 200, { ok: false, error: '出站调度器还没起' });
|
|
1489
|
+
const on = rt.outbound.setDry(body?.on === true);
|
|
1490
|
+
return json(res, 200, { ok: true, on });
|
|
1491
|
+
}
|
|
1492
|
+
|
|
1476
1493
|
// 配置读取(隐藏密钥)
|
|
1477
1494
|
if (pathname === '/api/config' && req.method === 'GET') {
|
|
1478
1495
|
const trust = resolveTrust(globalCfg);
|
|
@@ -1714,7 +1731,21 @@ async function startWebServerInstance({
|
|
|
1714
1731
|
|
|
1715
1732
|
// 插件
|
|
1716
1733
|
if (pathname === '/api/plugins' && req.method === 'GET') {
|
|
1717
|
-
|
|
1734
|
+
/**
|
|
1735
|
+
* E1:运行期错误的堆栈里可能带请求 URL / token,原样下发等于泄密。
|
|
1736
|
+
* 只脱敏错误相关字段,其余(名称、版本、开关)一个字节不动。
|
|
1737
|
+
*/
|
|
1738
|
+
const items = plugins.list().map((p) => ({
|
|
1739
|
+
...p,
|
|
1740
|
+
error: p.error ? redactText(p.error) : p.error,
|
|
1741
|
+
errorStack: p.errorStack ? redactText(p.errorStack) : p.errorStack,
|
|
1742
|
+
runtimeErrors: (p.runtimeErrors || []).map((e) => ({
|
|
1743
|
+
...e,
|
|
1744
|
+
message: redactText(e.message),
|
|
1745
|
+
stack: redactText(e.stack),
|
|
1746
|
+
})),
|
|
1747
|
+
}));
|
|
1748
|
+
return json(res, 200, items);
|
|
1718
1749
|
}
|
|
1719
1750
|
|
|
1720
1751
|
/**
|
package/web/app.js
CHANGED
|
@@ -704,6 +704,26 @@ function renderStatus(s) {
|
|
|
704
704
|
(s.counters.ignored ?? 0);
|
|
705
705
|
$('#c-err').textContent = `${s.counters.errors} / ${blocked}`;
|
|
706
706
|
|
|
707
|
+
/**
|
|
708
|
+
* E3:dry 出站截获。开着时不真发、只记下本来会发什么,点一下切换。
|
|
709
|
+
* 只影响本进程内建插件;外部子进程插件走 NDJSON,不经过 outbound。
|
|
710
|
+
*/
|
|
711
|
+
const dryEl = $('#c-dry');
|
|
712
|
+
if (dryEl) {
|
|
713
|
+
const on = Boolean(s.dry?.on);
|
|
714
|
+
dryEl.textContent = on ? `开 · ${s.dry?.recent?.length ?? 0} 条` : '关';
|
|
715
|
+
dryEl.style.cursor = 'pointer';
|
|
716
|
+
dryEl.onclick = async () => {
|
|
717
|
+
try {
|
|
718
|
+
const r = await api('/api/dry', { method: 'POST', body: JSON.stringify({ on: !on }) });
|
|
719
|
+
if (r?.ok) toast(r.on ? 'dry 模式已开:消息不会真发' : 'dry 模式已关');
|
|
720
|
+
else toast(r?.error || '切换失败');
|
|
721
|
+
} catch {
|
|
722
|
+
toast('切换失败:连不上面板接口');
|
|
723
|
+
}
|
|
724
|
+
};
|
|
725
|
+
}
|
|
726
|
+
|
|
707
727
|
$('#i-botid').textContent = s.botId || '-';
|
|
708
728
|
$('#i-gw').textContent = s.gatewayUrl || '-';
|
|
709
729
|
$('#i-session').textContent = shortId(s.sessionId);
|
|
@@ -2109,6 +2129,16 @@ async function loadPlugins() {
|
|
|
2109
2129
|
}</div>`
|
|
2110
2130
|
: ''
|
|
2111
2131
|
}
|
|
2132
|
+
${
|
|
2133
|
+
(p.runtimeErrors && p.runtimeErrors.length)
|
|
2134
|
+
? `<div class="err"><div>运行期错误(最近 ${p.runtimeErrors.length} 条,插件加载成功但每轮抛错):</div>
|
|
2135
|
+
${p.runtimeErrors.slice().reverse().map((e) =>
|
|
2136
|
+
`<details class="err-stack"><summary>${escapeHtml(
|
|
2137
|
+
new Date(e.at).toLocaleString('zh-CN'),
|
|
2138
|
+
)} · ${escapeHtml(e.message)}</summary><pre>${escapeHtml(e.stack || '')}</pre></details>`,
|
|
2139
|
+
).join('')}</div>`
|
|
2140
|
+
: ''
|
|
2141
|
+
}
|
|
2112
2142
|
${p.menuMissing ? '<div class="err">未提供指令菜单,用户看不到它能做什么</div>' : ''}
|
|
2113
2143
|
</div>
|
|
2114
2144
|
<span class="badge ${p.loaded ? 'on' : p.enabled ? '' : 'off'}">
|
|
@@ -3140,7 +3170,18 @@ function renderPPConfig() {
|
|
|
3140
3170
|
<div class="pp-hint pp-presets-tip" hidden></div>`
|
|
3141
3171
|
: '';
|
|
3142
3172
|
|
|
3143
|
-
|
|
3173
|
+
/**
|
|
3174
|
+
* 两个面板分属两个进程:想调「接话策略」的人常常跑去 DSH 能力页,
|
|
3175
|
+
* 想调「记不记得」的人又跑来这里(调研报告 §16.4-1)。各留一行指路。
|
|
3176
|
+
* 认插件用 schema 里的 `decide`(ai-chat 独有)兜底,光比 id 在改名后会失效。
|
|
3177
|
+
*/
|
|
3178
|
+
const isAiChat = PP.id === 'ai-chat' || Object.hasOwn(PP.schema || {}, 'decide');
|
|
3179
|
+
const crossHint = isAiChat
|
|
3180
|
+
? '<div class="pp-hint">记忆、心情、主动搭话、扩展不在这里,在 DSH 侧栏「能力」页;'
|
|
3181
|
+
+ '这一页只管什么时候接话、防吵、冷却和合并。</div>'
|
|
3182
|
+
: '';
|
|
3183
|
+
|
|
3184
|
+
box.innerHTML = crossHint + presetBar + keys
|
|
3144
3185
|
.map((k) => {
|
|
3145
3186
|
const s = PP.schema[k];
|
|
3146
3187
|
const v = PP.config?.[k] ?? s.default;
|
package/web/index.html
CHANGED
|
@@ -214,6 +214,9 @@
|
|
|
214
214
|
<div class="card"><div class="k">发出消息</div><div class="v" id="c-sent">0</div></div>
|
|
215
215
|
<div class="card"><div class="k">命令命中</div><div class="v" id="c-cmd">0</div></div>
|
|
216
216
|
<div class="card"><div class="k">错误 / 拦截</div><div class="v" id="c-err">0</div></div>
|
|
217
|
+
<div class="card" title="开着时消息不真发,只记下本来会发什么(只影响内建插件;点击切换)">
|
|
218
|
+
<div class="k">dry 模式</div><div class="v" id="c-dry">-</div>
|
|
219
|
+
</div>
|
|
217
220
|
</div>
|
|
218
221
|
|
|
219
222
|
<div class="row">
|