qq-bot-roost 1.1.7 → 1.1.8
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 +44 -13
- package/docs/AI/345/256/277/344/270/273/346/216/245/345/205/245.md +1 -1
- package/docs/DSH/346/216/245/345/205/245.md +3 -3
- package/docs//345/217/221/347/211/210/346/270/205/345/215/225.md +33 -21
- package/docs//345/256/277/344/270/273/345/215/217/350/256/256v1.md +19 -0
- package/docs//346/217/222/344/273/266/345/274/200/345/217/221/350/247/204/350/214/203.md +1 -1
- package/docs//346/236/266/346/236/204/350/257/264/346/230/216.md +1 -1
- package/docs//351/205/215/347/275/256/345/217/202/350/200/203.md +5 -0
- package/package.json +7 -6
- package/src/api.js +34 -4
- package/src/bot.js +8 -6
- package/src/check.js +141 -0
- package/src/delivery.js +5 -3
- package/src/doctor.js +26 -8
- package/src/gateway.js +26 -0
- package/src/gitee.js +6 -3
- package/src/host/dispatch.js +5 -0
- package/src/host/methods.js +26 -1
- package/src/ledger.js +69 -9
- package/src/main.js +29 -4
- package/src/message.js +11 -1
- package/src/mirror.js +7 -4
- package/src/onebot/actions.js +8 -0
- package/src/outbound.js +78 -18
- package/src/plugin/api-record.js +2 -0
- package/src/plugin/market.js +3 -3
- package/src/proxy.js +11 -1
- package/src/repo.js +22 -0
- package/src/storage/events-schema.js +32 -1
- package/src/storage/schema.js +29 -1
- package/src/updater.js +5 -5
- package/src/web/server.js +18 -15
- package/web/app.js +28 -6
- package/web/index.html +3 -3
package/src/check.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CLI 体检(`node src/main.js --check`)
|
|
3
|
+
* =====================================
|
|
4
|
+
*
|
|
5
|
+
* 承诺(README / `--help` 里写的那句):「只验证 AppID/AppSecret 和网关,不常驻」。
|
|
6
|
+
*
|
|
7
|
+
* ── 以前是什么样 ──
|
|
8
|
+
*
|
|
9
|
+
* `main.js` 里 `const CHECK_ONLY = args.has('--check')` 声明完**再没被引用过**。
|
|
10
|
+
* 于是这个命令什么也没检查,只是**照常把机器人全启起来**:加载插件、
|
|
11
|
+
* 起 OneBot / 宿主协议端口、`runtimes.start()` 真连网关、开面板、起定时任务。
|
|
12
|
+
* 用户按文档说「我只是检查一下」,结果是真上线了一只鸟——同 AppID 已有实例时
|
|
13
|
+
* 还会撞实例锁,报错看着像配置写错了。
|
|
14
|
+
*
|
|
15
|
+
* ── 现在做什么 ──
|
|
16
|
+
*
|
|
17
|
+
* 复用面板「检查」页那套 `runDoctor()`(同一份口径,不再各写一套),
|
|
18
|
+
* 去掉两项**只有常驻进程才有意义**的检查,再补一项真探网关:
|
|
19
|
+
*
|
|
20
|
+
* 1. `runDoctor()`:凭证、intents、插件目录可写、面板暴露面、SQLite…
|
|
21
|
+
* 2. 过滤 `connection` / `traffic`:这两项看的是「进程跑起来之后」的状态,
|
|
22
|
+
* 一次性体检里没有运行态,留着只会误导成「还没连上」。
|
|
23
|
+
* 3. 真探一次 `/gateway/bot`:验证凭证可用 + 接口可达。
|
|
24
|
+
* **不建 WebSocket、不注册实例、不起任何端口**。
|
|
25
|
+
*
|
|
26
|
+
* 全程只读配置,唯一的网络请求就是换 token 和取网关地址。
|
|
27
|
+
*/
|
|
28
|
+
import { TokenManager } from './token.js';
|
|
29
|
+
import { QQApi } from './api.js';
|
|
30
|
+
import { runDoctor, summarize } from './doctor.js';
|
|
31
|
+
|
|
32
|
+
/** 看的是常驻进程运行态,一次性体检里没有意义 */
|
|
33
|
+
const RUNTIME_ONLY = new Set(['connection', 'traffic']);
|
|
34
|
+
|
|
35
|
+
const MARK = { ok: '✔', warn: '!', error: '✘' };
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 造一个「只够体检用」的 api:有 token 管理器和 getGateway,没有 outbound、
|
|
39
|
+
* 没有 seqMap、不碰任何全局状态。**不经过 `BotRuntime.init()`**——那一步会
|
|
40
|
+
* 起 OneBot / 宿主协议端口并加载插件,已经不是检查了。
|
|
41
|
+
*
|
|
42
|
+
* @param {object} cfg 机器人配置
|
|
43
|
+
*/
|
|
44
|
+
export function defaultApiOf(cfg) {
|
|
45
|
+
const tokens = new TokenManager(cfg);
|
|
46
|
+
return { tokens, api: new QQApi({ tokenManager: tokens, baseUrl: cfg.baseUrl }) };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 真探一次网关地址。
|
|
51
|
+
* @param {object} api
|
|
52
|
+
*/
|
|
53
|
+
async function probeGateway(api) {
|
|
54
|
+
if (!api?.getGateway) {
|
|
55
|
+
return { id: 'gateway', level: 'warn', title: '网关未校验', detail: 'API 实例没建起来,跳过这一项' };
|
|
56
|
+
}
|
|
57
|
+
try {
|
|
58
|
+
const gw = await api.getGateway();
|
|
59
|
+
if (!gw?.url) throw new Error('网关接口未返回 url');
|
|
60
|
+
return { id: 'gateway', level: 'ok', title: '网关可达', detail: String(gw.url) };
|
|
61
|
+
} catch (e) {
|
|
62
|
+
return {
|
|
63
|
+
id: 'gateway',
|
|
64
|
+
level: 'error',
|
|
65
|
+
title: '网关不可达',
|
|
66
|
+
detail: e.message,
|
|
67
|
+
fix: '检查 AppID / AppSecret、机器人是否已上线、网络或代理设置(面板「设置 → 网络」)。',
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* 跑一遍 CLI 体检。
|
|
74
|
+
*
|
|
75
|
+
* @param {object} p
|
|
76
|
+
* @param {Array<{id?:string, cfg:object, mock?:boolean}>} p.bots 机器人配置(**未启动**)
|
|
77
|
+
* @param {object} p.globalCfg 全局配置
|
|
78
|
+
* @param {boolean} [p.mock] 全局 mock 模式(`--mock --check`)
|
|
79
|
+
* @param {(line:string)=>void} [p.print]
|
|
80
|
+
* @param {boolean} [p.probe] 是否真探网关(测试关掉,避免联网)
|
|
81
|
+
* @param {(cfg:object)=>{tokens:object, api:object}} [p.makeApi] 测试注入
|
|
82
|
+
* @returns {Promise<number>} 进程退出码:0 无 error,1 有 error
|
|
83
|
+
*/
|
|
84
|
+
export async function runCheckMode({
|
|
85
|
+
bots,
|
|
86
|
+
globalCfg,
|
|
87
|
+
mock = false,
|
|
88
|
+
print = (line) => console.log(line),
|
|
89
|
+
probe = true,
|
|
90
|
+
makeApi = defaultApiOf,
|
|
91
|
+
}) {
|
|
92
|
+
if (!Array.isArray(bots) || !bots.length) {
|
|
93
|
+
print('没有可体检的机器人:检查 config/bots/*.json 里的 enabled');
|
|
94
|
+
return 1;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
let code = 0;
|
|
98
|
+
for (const b of bots) {
|
|
99
|
+
const cfg = b?.cfg ?? b ?? {};
|
|
100
|
+
const id = String(cfg.id ?? b?.id ?? 'main');
|
|
101
|
+
const isMock = Boolean(b?.mock ?? mock);
|
|
102
|
+
print(`\n—— 体检:${id}${cfg.name && cfg.name !== id ? `(${cfg.name})` : ''} ——`);
|
|
103
|
+
|
|
104
|
+
let made = null;
|
|
105
|
+
try {
|
|
106
|
+
made = makeApi(cfg);
|
|
107
|
+
} catch (e) {
|
|
108
|
+
print(` ${MARK.error} 无法初始化接口客户端:${e.message}`);
|
|
109
|
+
code = 1;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** doctor 只读这个壳子里的 `api.tokens` / `mock` / `state`,不需要真运行时 */
|
|
114
|
+
const rt = { id, cfg, state: 'check', mock: isMock, api: made };
|
|
115
|
+
|
|
116
|
+
let list;
|
|
117
|
+
try {
|
|
118
|
+
list = (await runDoctor({ cfg, globalCfg, rt, mock: isMock })).filter((x) => !RUNTIME_ONLY.has(x.id));
|
|
119
|
+
} catch (e) {
|
|
120
|
+
print(` ${MARK.error} 体检本身出错:${e.message}`);
|
|
121
|
+
code = 1;
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (probe && !isMock) list.push(await probeGateway(made?.api));
|
|
126
|
+
|
|
127
|
+
for (const it of list) {
|
|
128
|
+
print(` ${MARK[it.level] ?? '·'} ${it.title}:${it.detail}`);
|
|
129
|
+
if (it.fix) print(` → ${it.fix}`);
|
|
130
|
+
}
|
|
131
|
+
if (list.some((x) => x.level === 'error')) code = 1;
|
|
132
|
+
print(` 小结:${summarize(list)}`);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
print(
|
|
136
|
+
code
|
|
137
|
+
? '\n体检未通过:按上面的提示改完再跑一次(本次没有启动任何机器人)'
|
|
138
|
+
: '\n体检通过(本次没有启动任何机器人、没有连 WebSocket)',
|
|
139
|
+
);
|
|
140
|
+
return code;
|
|
141
|
+
}
|
package/src/delivery.js
CHANGED
|
@@ -85,13 +85,14 @@ export function createDeliveryLedger({ db, botId, log = () => {} }) {
|
|
|
85
85
|
* @param {string} [p.replyTo] 被动回复时的 msg_id
|
|
86
86
|
* @param {number} [p.msgSeq]
|
|
87
87
|
* @param {string} p.digest
|
|
88
|
+
* @param {string} [p.source] 来源(plugin / host / onebot / api),见 `events-schema.js`
|
|
88
89
|
* @returns {{action:'send'|'reuse'|'unknown'|'wait', row?:object}}
|
|
89
90
|
* - `send` 没发过 / 上次 failed,可以发
|
|
90
91
|
* - `reuse` 已经 sent/audited,直接返回上次结果
|
|
91
92
|
* - `unknown` 上次结果未知,**不能重发**
|
|
92
93
|
* - `wait` 正在发送中(并发调用)
|
|
93
94
|
*/
|
|
94
|
-
function claim({ requestId, kind, chatId, replyTo, msgSeq, digest }) {
|
|
95
|
+
function claim({ requestId, kind, chatId, replyTo, msgSeq, digest, source = '' }) {
|
|
95
96
|
if (!ready()) return { action: 'send' };
|
|
96
97
|
const id = String(requestId ?? '').trim();
|
|
97
98
|
if (!id) return { action: 'send' };
|
|
@@ -101,8 +102,8 @@ export function createDeliveryLedger({ db, botId, log = () => {} }) {
|
|
|
101
102
|
if (!row) {
|
|
102
103
|
db.prepare(
|
|
103
104
|
`INSERT INTO deliveries
|
|
104
|
-
(request_id, bot_id, kind, chat_id, reply_to, msg_seq, digest, state, attempts, created_at)
|
|
105
|
-
VALUES (
|
|
105
|
+
(request_id, bot_id, kind, chat_id, reply_to, msg_seq, digest, state, attempts, created_at, source)
|
|
106
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?)`,
|
|
106
107
|
).run(
|
|
107
108
|
id,
|
|
108
109
|
botId,
|
|
@@ -114,6 +115,7 @@ export function createDeliveryLedger({ db, botId, log = () => {} }) {
|
|
|
114
115
|
DELIVERY_STATE.PENDING,
|
|
115
116
|
0,
|
|
116
117
|
Date.now(),
|
|
118
|
+
String(source ?? ''),
|
|
117
119
|
);
|
|
118
120
|
return { action: 'send' };
|
|
119
121
|
}
|
package/src/doctor.js
CHANGED
|
@@ -132,17 +132,35 @@ export async function runDoctor({ cfg, globalCfg, rt, mock = false }) {
|
|
|
132
132
|
}
|
|
133
133
|
|
|
134
134
|
/* ---------- 4. 插件目录可写 ---------- */
|
|
135
|
+
/**
|
|
136
|
+
* 三种情况必须分开说,不能一刀切成「不可写」:
|
|
137
|
+
* · 存在且可写 → ok
|
|
138
|
+
* · 不存在 → warn。全新安装 / 全新检出时本来就没有(`plugins/` 在
|
|
139
|
+
* `.gitignore` 里),首次启动 `ensureDirs` 会建出来。
|
|
140
|
+
* 报 error 会让刚 clone 完就跑 `--check` 的人看到
|
|
141
|
+
* 「装插件会失败」这种根本不存在的故障,还会让退出码变成 1。
|
|
142
|
+
* · 存在但不可写 → error。这才是真问题(权限、被杀毒软件锁住)。
|
|
143
|
+
*/
|
|
135
144
|
try {
|
|
136
145
|
await fs.access(DIRS.plugins, FS.W_OK);
|
|
137
146
|
add('plugins-dir', 'ok', '插件目录可写', DIRS.plugins);
|
|
138
|
-
} catch {
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
147
|
+
} catch (e) {
|
|
148
|
+
if (e?.code === 'ENOENT') {
|
|
149
|
+
add(
|
|
150
|
+
'plugins-dir',
|
|
151
|
+
'warn',
|
|
152
|
+
'插件目录还没建',
|
|
153
|
+
`${DIRS.plugins} 不存在——全新安装时这是正常的,首次启动会自动创建。`,
|
|
154
|
+
);
|
|
155
|
+
} else {
|
|
156
|
+
add(
|
|
157
|
+
'plugins-dir',
|
|
158
|
+
'error',
|
|
159
|
+
'插件目录不可写',
|
|
160
|
+
`${DIRS.plugins} 打不开或没有写权限,装插件会失败。`,
|
|
161
|
+
'检查目录是否被杀毒软件锁住、当前用户有没有权限。',
|
|
162
|
+
);
|
|
163
|
+
}
|
|
146
164
|
}
|
|
147
165
|
|
|
148
166
|
/* ---------- 5. 面板暴露面 ---------- */
|
package/src/gateway.js
CHANGED
|
@@ -63,6 +63,14 @@ export class Gateway {
|
|
|
63
63
|
this.heartbeatInterval = 45000;
|
|
64
64
|
this.lastAckAt = 0;
|
|
65
65
|
this.connecting = false;
|
|
66
|
+
/**
|
|
67
|
+
* 建连代数。`stop()` 每调一次就 +1,`#connect()` 在 await 前后各对一次。
|
|
68
|
+
*
|
|
69
|
+
* 只靠 `stopped` 标志不够:`restart()` 会在 stop 之后把 stopped 改回 false,
|
|
70
|
+
* 这时**上一轮还在 await 的 #connect 会以为没事了**,继续建第二条连接。
|
|
71
|
+
* 加个代数就分得清「谁是我这一轮的」。
|
|
72
|
+
*/
|
|
73
|
+
this.epoch = 0;
|
|
66
74
|
/** 已经为哪条 ws 安排过重连,防止 error + close 双触发建出两条连接 */
|
|
67
75
|
this.retryScheduledFor = null;
|
|
68
76
|
|
|
@@ -131,6 +139,9 @@ export class Gateway {
|
|
|
131
139
|
|
|
132
140
|
stop() {
|
|
133
141
|
this.stopped = true;
|
|
142
|
+
/** 作废所有在飞的 `#connect()`,并把 connecting 复位,别让 restart() 被卡住 */
|
|
143
|
+
this.epoch += 1;
|
|
144
|
+
this.connecting = false;
|
|
134
145
|
this.#clearTimers();
|
|
135
146
|
try {
|
|
136
147
|
this.ws?.close(1000, 'client shutdown');
|
|
@@ -159,6 +170,8 @@ export class Gateway {
|
|
|
159
170
|
return;
|
|
160
171
|
}
|
|
161
172
|
this.connecting = true;
|
|
173
|
+
/** 这一轮建连的代号;stop()/restart() 会让它过期(见构造函数里的说明) */
|
|
174
|
+
const epoch = this.epoch;
|
|
162
175
|
let url;
|
|
163
176
|
try {
|
|
164
177
|
const gw = await this.api.getGateway();
|
|
@@ -172,6 +185,19 @@ export class Gateway {
|
|
|
172
185
|
return this.#scheduleReconnect();
|
|
173
186
|
}
|
|
174
187
|
|
|
188
|
+
/**
|
|
189
|
+
* 取地址是异步的(最长 15 秒),这期间可能已经被 stop():
|
|
190
|
+
* 下线、删除机器人、面板重启都会走到。这里必须复查一次,否则会在停机后
|
|
191
|
+
* 建出一条**僵尸连接**——它能连上就会发 Identify,把线上那条会话踢成
|
|
192
|
+
* 4902(本文件开头那段「两条连接互相踢」说的就是它),而且 `connecting`
|
|
193
|
+
* 会永久停在 true。
|
|
194
|
+
*/
|
|
195
|
+
if (this.stopped || epoch !== this.epoch) {
|
|
196
|
+
this.connecting = false;
|
|
197
|
+
log.debug('停机中,放弃建立连接');
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
|
|
175
201
|
const ws = new WebSocket(url);
|
|
176
202
|
this.ws = ws;
|
|
177
203
|
|
package/src/gitee.js
CHANGED
|
@@ -28,6 +28,9 @@ import fs from 'node:fs/promises';
|
|
|
28
28
|
import path from 'node:path';
|
|
29
29
|
import { createLogger } from './logger.js';
|
|
30
30
|
import { netFetch } from './proxy.js';
|
|
31
|
+
import { giteeRepoOf } from './repo.js';
|
|
32
|
+
|
|
33
|
+
export { giteeRepoOf };
|
|
31
34
|
|
|
32
35
|
const log = createLogger('gitee');
|
|
33
36
|
|
|
@@ -55,12 +58,12 @@ export function giteeRawUrl(repo, ref, filePath) {
|
|
|
55
58
|
.split('/')
|
|
56
59
|
.map((s) => encodeURIComponent(s))
|
|
57
60
|
.join('/');
|
|
58
|
-
return `https://gitee.com/${repo}/raw/${encodeURIComponent(ref)}/${p}`;
|
|
61
|
+
return `https://gitee.com/${giteeRepoOf(repo)}/raw/${encodeURIComponent(ref)}/${p}`;
|
|
59
62
|
}
|
|
60
63
|
|
|
61
64
|
/** blob 地址:`https://gitee.com/api/v5/repos/{repo}/git/blobs/{sha}` */
|
|
62
65
|
export function giteeBlobUrl(repo, sha) {
|
|
63
|
-
return `${API}/repos/${repo}/git/blobs/${encodeURIComponent(sha)}`;
|
|
66
|
+
return `${API}/repos/${giteeRepoOf(repo)}/git/blobs/${encodeURIComponent(sha)}`;
|
|
64
67
|
}
|
|
65
68
|
|
|
66
69
|
/**
|
|
@@ -133,7 +136,7 @@ export async function fetchGiteeTree({
|
|
|
133
136
|
// 1) 列清单(整个下载只用这一次 API)
|
|
134
137
|
const q = new URLSearchParams({ recursive: '1' });
|
|
135
138
|
if (token) q.set('access_token', token);
|
|
136
|
-
const apiUrl = `${API}/repos/${repo}/git/trees/${encodeURIComponent(ref)}?${q}`;
|
|
139
|
+
const apiUrl = `${API}/repos/${giteeRepoOf(repo)}/git/trees/${encodeURIComponent(ref)}?${q}`;
|
|
137
140
|
let tree;
|
|
138
141
|
try {
|
|
139
142
|
const res = await netFetch(apiUrl, {
|
package/src/host/dispatch.js
CHANGED
|
@@ -110,6 +110,11 @@ export async function sendOut({
|
|
|
110
110
|
...(rid ? { requestId: rid } : {}),
|
|
111
111
|
...(fileType != null ? { fileType: Number(fileType) } : {}),
|
|
112
112
|
plugin: HOST_PLUGIN,
|
|
113
|
+
/**
|
|
114
|
+
* 来源标记(账本 v4):自有宿主协议发起的,和 OneBot / 框架插件区分开。
|
|
115
|
+
* `plugin='host'` 只说明「署名是宿主」,`source` 才是「从哪个口子出去的」。
|
|
116
|
+
*/
|
|
117
|
+
source: 'host',
|
|
113
118
|
});
|
|
114
119
|
return {
|
|
115
120
|
id: String(r?.id ?? ''),
|
package/src/host/methods.js
CHANGED
|
@@ -23,7 +23,7 @@ import { registerMedia } from './media.js';
|
|
|
23
23
|
import { splitQuery } from '../search-query.js';
|
|
24
24
|
import { registerOps } from './ops.js';
|
|
25
25
|
import { registerDev } from './dev.js';
|
|
26
|
-
import { sendOut, receivedAtOf, isChatKind, CHAT_KINDS } from './dispatch.js';
|
|
26
|
+
import { sendOut, receivedAtOf, isChatKind, CHAT_KINDS, HOST_PLUGIN } from './dispatch.js';
|
|
27
27
|
|
|
28
28
|
export const HOST_PROTOCOL = 1;
|
|
29
29
|
|
|
@@ -663,6 +663,31 @@ export function createMethods({ runtime: R, getState, log = () => {}, extBridge
|
|
|
663
663
|
/** 首片返回的 stream_msg_id 也映射到同一个 seq,续片只带它也能对上 */
|
|
664
664
|
const sid = str(data?.stream_msg_id ?? data?.id);
|
|
665
665
|
if (sid && !streamSeqs.has(sid)) streamSeqs.set(sid, { seq, at: Date.now() });
|
|
666
|
+
/**
|
|
667
|
+
* 流式**不入 outbound**,也就没有 outbound 自带的那两个记账出口。
|
|
668
|
+
* 以前宿主流式发出去的消息在账本里一条都没有——「自有协议说的话」
|
|
669
|
+
* 整类不可见,出了问题只能翻日志。
|
|
670
|
+
*
|
|
671
|
+
* 这里按插件侧同一口径补记:**只在结束片(state=10)记一笔**,
|
|
672
|
+
* 否则一条长回复会在账本里冒出十几行。正文记的是结束片的内容
|
|
673
|
+
* (协议只给增量,宿主要完整全文得自己拼),和 `api-record.js`
|
|
674
|
+
* 对 `sendStreamMessage` 的处理一致。
|
|
675
|
+
*/
|
|
676
|
+
if (state === 10) {
|
|
677
|
+
try {
|
|
678
|
+
R.outbound?.recordDirect?.({
|
|
679
|
+
kind: 'c2c',
|
|
680
|
+
target: openid,
|
|
681
|
+
content,
|
|
682
|
+
payload: { content },
|
|
683
|
+
plugin: HOST_PLUGIN,
|
|
684
|
+
source: 'host',
|
|
685
|
+
id: sid || key,
|
|
686
|
+
});
|
|
687
|
+
} catch {
|
|
688
|
+
/* 记账是增强,失败不影响发送 */
|
|
689
|
+
}
|
|
690
|
+
}
|
|
666
691
|
return { ...(data ?? {}), msgSeq: opts.msgSeq };
|
|
667
692
|
});
|
|
668
693
|
|
package/src/ledger.js
CHANGED
|
@@ -48,7 +48,7 @@ import { SENSITIVE_KEY } from './runtime.js';
|
|
|
48
48
|
* 单独用 `AUTHOR_COLS` 把它用 `json_extract` 拆成三列——一页 50 条每条
|
|
49
49
|
* 几十 KB 的报文全都读上来太浪费。
|
|
50
50
|
*/
|
|
51
|
-
const EVENT_COLS = 'seq, id, kind, chat_id, user_id, user_name, content, at, time_basis, msg_idx, quoted, trace, plugin, bot_id';
|
|
51
|
+
const EVENT_COLS = 'seq, id, kind, chat_id, user_id, user_name, content, at, time_basis, msg_idx, quoted, trace, plugin, source, bot_id';
|
|
52
52
|
|
|
53
53
|
/** 从 `payload.author` 里取的三个展示字段(昵称 / 群名片 / 头像) */
|
|
54
54
|
const AUTHOR_COLS = `,
|
|
@@ -230,6 +230,12 @@ export class EventLedger {
|
|
|
230
230
|
: `${this.botId}:${msg.chatId ?? ''}:${at}:${digestOf(msg)}`;
|
|
231
231
|
|
|
232
232
|
const id = crypto.randomUUID();
|
|
233
|
+
/**
|
|
234
|
+
* 来源(v4)的兜底:显式给了就用,没给但署名了插件 → 一定是插件路径。
|
|
235
|
+
* 和 `outbound.js` 的 `sourceOf()` 同一口径(那边是给投递账本用的,
|
|
236
|
+
* 两层各存一份库、都得算)。两者都空就是空串 = 不知道,**不等于入站**。
|
|
237
|
+
*/
|
|
238
|
+
const source = String(msg.source ?? '') || (msg.plugin ? 'plugin' : '');
|
|
233
239
|
const payload = (() => {
|
|
234
240
|
try {
|
|
235
241
|
let s = JSON.stringify(cleanPayload(msg.raw));
|
|
@@ -251,8 +257,8 @@ export class EventLedger {
|
|
|
251
257
|
`INSERT OR IGNORE INTO events
|
|
252
258
|
(id, bot_id, kind, chat_id, msg_id, user_id, user_name, content,
|
|
253
259
|
at, observed_at, time_basis, dedupe,
|
|
254
|
-
msg_idx, ref_msg_idx, union_openid, quoted, payload, trace, plugin)
|
|
255
|
-
VALUES (
|
|
260
|
+
msg_idx, ref_msg_idx, union_openid, quoted, payload, trace, plugin, source)
|
|
261
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
|
256
262
|
)
|
|
257
263
|
.run(
|
|
258
264
|
id,
|
|
@@ -279,6 +285,13 @@ export class EventLedger {
|
|
|
279
285
|
* 多插件合并时是逗号分隔(`echo,ai-chat`)。
|
|
280
286
|
*/
|
|
281
287
|
String(msg.plugin ?? ''),
|
|
288
|
+
/**
|
|
289
|
+
* 从哪个口子进来 / 出去(v4)。见 `events-schema.js` 的取值口径。
|
|
290
|
+
* 入站由 `bot.dispatch()` 传(gateway / webhook / mock),
|
|
291
|
+
* 出站由 `outbound.send({source})` 传(plugin / host / onebot / api)。
|
|
292
|
+
* 老调用方不给就写空串——**空串表示「不知道」,不是「入站」**。
|
|
293
|
+
*/
|
|
294
|
+
source,
|
|
282
295
|
);
|
|
283
296
|
// changes === 0 说明撞了 dedupe 唯一约束 = 官方重推的同一条消息
|
|
284
297
|
if (!r?.changes) {
|
|
@@ -422,7 +435,7 @@ export class EventLedger {
|
|
|
422
435
|
.get(this.botId, String(chatId), Number(anchorSeq) || 0);
|
|
423
436
|
if (!anchor) return [];
|
|
424
437
|
|
|
425
|
-
const cols = `seq, id, kind, chat_id, msg_id, user_id, user_name, content, at, time_basis, msg_idx, ref_msg_idx, quoted`;
|
|
438
|
+
const cols = `seq, id, kind, chat_id, msg_id, user_id, user_name, content, at, time_basis, msg_idx, ref_msg_idx, quoted, source`;
|
|
426
439
|
const prev = this.db
|
|
427
440
|
.prepare(
|
|
428
441
|
/**
|
|
@@ -461,6 +474,8 @@ export class EventLedger {
|
|
|
461
474
|
msgIdx: r.msg_idx,
|
|
462
475
|
refMsgIdx: r.ref_msg_idx,
|
|
463
476
|
quoted: r.quoted,
|
|
477
|
+
/** 邻文也带来源:AI 拿到上下文时能知道哪条是 OneBot/宿主发的 */
|
|
478
|
+
source: r.source ?? '',
|
|
464
479
|
content: contentOf(r),
|
|
465
480
|
role: r.hit ? 'hit' : 'neighbor',
|
|
466
481
|
}));
|
|
@@ -680,14 +695,14 @@ export class EventLedger {
|
|
|
680
695
|
const rows = beforeSeq
|
|
681
696
|
? this.db
|
|
682
697
|
.prepare(
|
|
683
|
-
`SELECT
|
|
698
|
+
`SELECT ${EVENT_COLS}, payload
|
|
684
699
|
FROM events WHERE bot_id = ? AND chat_id = ? AND seq < ? AND kind != 'notice'
|
|
685
700
|
ORDER BY seq DESC LIMIT ?`,
|
|
686
701
|
)
|
|
687
702
|
.all(this.botId, String(chatId), Number(beforeSeq), lim)
|
|
688
703
|
: this.db
|
|
689
704
|
.prepare(
|
|
690
|
-
`SELECT
|
|
705
|
+
`SELECT ${EVENT_COLS}, payload
|
|
691
706
|
FROM events WHERE bot_id = ? AND chat_id = ? AND kind != 'notice'
|
|
692
707
|
ORDER BY seq DESC LIMIT ?`,
|
|
693
708
|
)
|
|
@@ -723,7 +738,7 @@ export class EventLedger {
|
|
|
723
738
|
const lim = Math.min(Math.max(Number(limit) || 20, 1), 200);
|
|
724
739
|
const rows = this.db
|
|
725
740
|
.prepare(
|
|
726
|
-
`SELECT
|
|
741
|
+
`SELECT ${EVENT_COLS}
|
|
727
742
|
FROM events WHERE bot_id = ? AND user_id = ? AND kind != 'notice'
|
|
728
743
|
ORDER BY at DESC, seq DESC LIMIT ?`,
|
|
729
744
|
)
|
|
@@ -949,7 +964,9 @@ export class EventLedger {
|
|
|
949
964
|
* · 有 `msgId` → dedupe = `botId:msgId`,和原来那条一模一样;
|
|
950
965
|
* · 没有 `msgId` → dedupe 里带 `at`,同一份文件导两次也只会进一次。
|
|
951
966
|
*
|
|
952
|
-
* @param {Array<object>} rows 每行 `{at, kind, chatId, msgId, userId, userName, content, plugin}`
|
|
967
|
+
* @param {Array<object>} rows 每行 `{at, kind, chatId, msgId, userId, userName, content, plugin, source}`
|
|
968
|
+
* `source` 缺省落 `import`(这条是外部搬进来的),给了就按给的记——导出文件里带的
|
|
969
|
+
* `gateway` / `onebot` / `plugin` 原样还原,别把来源洗成清一色的 `import`。
|
|
953
970
|
* @returns {{added:number, skipped:number, bad:number, error?:string}}
|
|
954
971
|
*/
|
|
955
972
|
importRows(rows, { max = 5000 } = {}) {
|
|
@@ -979,6 +996,12 @@ export class EventLedger {
|
|
|
979
996
|
userName: String(r?.userName ?? ''),
|
|
980
997
|
content: String(r?.content ?? ''),
|
|
981
998
|
plugin: String(r?.plugin ?? ''),
|
|
999
|
+
/**
|
|
1000
|
+
* 导入的行默认标 `import`:这些是从外部搬进来的历史,
|
|
1001
|
+
* 不是「现在从网关收到的」。允许行里显式覆盖(比如从 OneBot
|
|
1002
|
+
* 历史接口搬进来的,标 `onebot` 更准确)。
|
|
1003
|
+
*/
|
|
1004
|
+
source: String(r?.source ?? 'import'),
|
|
982
1005
|
/**
|
|
983
1006
|
* `append()` 只从 `raw.timestamp` 推 `at`(传 `at` 无效)。
|
|
984
1007
|
* 给 ISO 字符串,`resolveTime` 会解析成 `basis: 'message'`——
|
|
@@ -1051,7 +1074,7 @@ export class EventLedger {
|
|
|
1051
1074
|
const args = [];
|
|
1052
1075
|
if (chat) { where.push('chat_id = ?'); args.push(chat); }
|
|
1053
1076
|
if (ts) { where.push('at < ?'); args.push(ts); }
|
|
1054
|
-
const sql = `SELECT seq, id, kind, chat_id, msg_id, user_id, user_name, content, at, time_basis, plugin, bot_id
|
|
1077
|
+
const sql = `SELECT seq, id, kind, chat_id, msg_id, user_id, user_name, content, at, time_basis, plugin, source, bot_id
|
|
1055
1078
|
FROM events ${where.length ? `WHERE ${where.join(' AND ')}` : ''}
|
|
1056
1079
|
ORDER BY seq ASC LIMIT ?`;
|
|
1057
1080
|
return this.db.prepare(sql).all(...args, lim);
|
|
@@ -1114,6 +1137,15 @@ function mapRow(r) {
|
|
|
1114
1137
|
* 别默认成 `''` 就当成"入站"——老库里的出站行也是空串。
|
|
1115
1138
|
*/
|
|
1116
1139
|
plugin: r.plugin ?? '',
|
|
1140
|
+
/**
|
|
1141
|
+
* 从哪个口子进来 / 出去(v4):gateway / webhook / plugin / host /
|
|
1142
|
+
* onebot / api / mock / dev / import。
|
|
1143
|
+
*
|
|
1144
|
+
* 和 `plugin` 是**两个维度**:`plugin='' + source='onebot'` 是「OneBot
|
|
1145
|
+
* 客户端发的」,`plugin='ai-chat' + source='plugin'` 是「ai-chat 插件发的」。
|
|
1146
|
+
* 老行一律空串,表示「不知道」,不要拿来判断入站还是出站。
|
|
1147
|
+
*/
|
|
1148
|
+
source: r.source ?? '',
|
|
1117
1149
|
content: contentOf(r),
|
|
1118
1150
|
};
|
|
1119
1151
|
}
|
|
@@ -1135,6 +1167,34 @@ function authorFieldsOf(r) {
|
|
|
1135
1167
|
};
|
|
1136
1168
|
}
|
|
1137
1169
|
|
|
1170
|
+
/**
|
|
1171
|
+
* 把一行事件(库里的 snake_case)转成**导入用的 camelCase**。
|
|
1172
|
+
*
|
|
1173
|
+
* 导出 JSONL 与 `importRows()` 必须共用这一份映射。以前导出那边自己手写字段列表,
|
|
1174
|
+
* 加 `source` 时漏了——而 JSONL 恰恰是「给导回用」的格式,导一轮回来来源全变成
|
|
1175
|
+
* `import`,等于备份自己丢了信息。放在模块级是为了能直接单测(给一行库记录,
|
|
1176
|
+
* 断言导出的对象),不用起面板。
|
|
1177
|
+
*
|
|
1178
|
+
* @param {object} r `exportRows()` 返回的行
|
|
1179
|
+
*/
|
|
1180
|
+
export function toImportRow(r) {
|
|
1181
|
+
return {
|
|
1182
|
+
at: Number(r?.at),
|
|
1183
|
+
kind: String(r?.kind ?? ''),
|
|
1184
|
+
chatId: String(r?.chat_id ?? ''),
|
|
1185
|
+
msgId: String(r?.msg_id ?? ''),
|
|
1186
|
+
userId: String(r?.user_id ?? ''),
|
|
1187
|
+
userName: String(r?.user_name ?? ''),
|
|
1188
|
+
content: String(r?.content ?? ''),
|
|
1189
|
+
plugin: String(r?.plugin ?? ''),
|
|
1190
|
+
/**
|
|
1191
|
+
* 来源必须原样带出去。`importRows()` 只在**缺这个字段**时才落 `import`,
|
|
1192
|
+
* 所以「网关收的」导回去还是 `gateway`,「OneBot 客户端发的」还是 `onebot`。
|
|
1193
|
+
*/
|
|
1194
|
+
source: String(r?.source ?? ''),
|
|
1195
|
+
};
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1138
1198
|
/**
|
|
1139
1199
|
* @param {object} p
|
|
1140
1200
|
* @param {string} p.file
|
package/src/main.js
CHANGED
|
@@ -17,6 +17,7 @@ import { createLogger, setLevel, getLevel, attachLogFile, flushLogs } from './lo
|
|
|
17
17
|
import { configureMirror } from './mirror.js';
|
|
18
18
|
import { configureProxy } from './proxy.js';
|
|
19
19
|
import { BotRuntime, pluginAllowedIn } from './bot.js';
|
|
20
|
+
import { runCheckMode } from './check.js';
|
|
20
21
|
import { toggleGroupPlugin, resetGroupPlugins, describeGroupScope } from './plugin/groupscope.js';
|
|
21
22
|
import { runtime, sanitizePayload } from './runtime.js';
|
|
22
23
|
import { LEVEL, NO_PERM, levelName, parseLevel, parseScope, scopeOf } from './roles.js';
|
|
@@ -70,7 +71,7 @@ qq-bot-roost(栖 Roost)· QQ 机器人框架
|
|
|
70
71
|
用法:
|
|
71
72
|
node src/main.js 连接 QQ,正常跑(会自动打开面板)
|
|
72
73
|
node src/main.js --no-open 同上,但不自动开浏览器
|
|
73
|
-
node src/main.js --check
|
|
74
|
+
node src/main.js --check 只体检:凭证 / 网关 / intents / 面板暴露面,不启动机器人
|
|
74
75
|
node src/main.js --mock 不连 QQ,用本地假消息开发插件
|
|
75
76
|
node src/main.js --mock --serve 只启动可视化面板,不读标准输入(调界面用)
|
|
76
77
|
node src/main.js --paused 启动时先全局暂停,确认配置无误后在面板放开
|
|
@@ -984,12 +985,12 @@ async function runMock(runtimes) {
|
|
|
984
985
|
group_openid: gid,
|
|
985
986
|
op_member_openid: inviter,
|
|
986
987
|
timestamp: String(Date.now()),
|
|
987
|
-
});
|
|
988
|
+
}, 'mock');
|
|
988
989
|
}
|
|
989
990
|
if (t.startsWith('!delbot')) {
|
|
990
991
|
const [, gid = fakeGroup] = t.split(/\s+/);
|
|
991
992
|
console.log(`[模拟] ${cur.id} 被移出群 ${gid}`);
|
|
992
|
-
return cur.dispatch('GROUP_DEL_ROBOT', { group_openid: gid, timestamp: String(Date.now()) });
|
|
993
|
+
return cur.dispatch('GROUP_DEL_ROBOT', { group_openid: gid, timestamp: String(Date.now()) }, 'mock');
|
|
993
994
|
}
|
|
994
995
|
|
|
995
996
|
return cur.dispatch('GROUP_AT_MESSAGE_CREATE', {
|
|
@@ -998,7 +999,7 @@ async function runMock(runtimes) {
|
|
|
998
999
|
group_openid: fakeGroup,
|
|
999
1000
|
author: { member_openid: currentUser() },
|
|
1000
1001
|
timestamp: String(Date.now()),
|
|
1001
|
-
});
|
|
1002
|
+
}, 'mock');
|
|
1002
1003
|
};
|
|
1003
1004
|
|
|
1004
1005
|
const send = (line) => {
|
|
@@ -1138,6 +1139,30 @@ async function main() {
|
|
|
1138
1139
|
botCfgs = [await loadBotConfig(id)];
|
|
1139
1140
|
}
|
|
1140
1141
|
|
|
1142
|
+
/**
|
|
1143
|
+
* `--check`:**只体检,不常驻**。
|
|
1144
|
+
*
|
|
1145
|
+
* 位置很关键,必须在这三件事之前:
|
|
1146
|
+
* · 建运行时(`rt.init()` 会起 OneBot / 宿主协议端口、加载插件、建 SQLite);
|
|
1147
|
+
* · Webhook 服务(会占端口);
|
|
1148
|
+
* · 配置快照(会写盘)。
|
|
1149
|
+
* 以前 `CHECK_ONLY` 声明完就没再被引用过,这个命令等于「照常启动」——
|
|
1150
|
+
* 用户以为只是检查,实际真上线了一只鸟。
|
|
1151
|
+
*/
|
|
1152
|
+
if (CHECK_ONLY) {
|
|
1153
|
+
const code = await runCheckMode({
|
|
1154
|
+
bots: botCfgs.filter((c) => c.enabled !== false),
|
|
1155
|
+
globalCfg,
|
|
1156
|
+
mock: MOCK,
|
|
1157
|
+
});
|
|
1158
|
+
try {
|
|
1159
|
+
await flushLogs();
|
|
1160
|
+
} catch {
|
|
1161
|
+
/* 日志没刷出去不影响退出码 */
|
|
1162
|
+
}
|
|
1163
|
+
process.exit(code);
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1141
1166
|
/**
|
|
1142
1167
|
* 启动时给所有机器人配置拍一份快照。
|
|
1143
1168
|
*
|
package/src/message.js
CHANGED
|
@@ -291,7 +291,7 @@ export function parseElements(list, depth = 0) {
|
|
|
291
291
|
* @param {object} [p.identity] 身份对照表(`IdentityStore`)。没传就是没启用绑定,
|
|
292
292
|
* 所有 `uin` / `*Aliases` 字段一律空,老行为不变。
|
|
293
293
|
*/
|
|
294
|
-
export function buildMessage(eventName, d, { api, cfg, outbound, session, traceId, identity }) {
|
|
294
|
+
export function buildMessage(eventName, d, { api, cfg, outbound, session, traceId, identity, source = '' }) {
|
|
295
295
|
const kind = messageKindOf(eventName) ?? 'unknown';
|
|
296
296
|
|
|
297
297
|
let groupId = '';
|
|
@@ -382,6 +382,14 @@ export function buildMessage(eventName, d, { api, cfg, outbound, session, traceI
|
|
|
382
382
|
* 让插件生成会出现「同一条消息被两个插件各生成一个 id」。
|
|
383
383
|
*/
|
|
384
384
|
traceId: String(traceId || newTraceId()),
|
|
385
|
+
/**
|
|
386
|
+
* 这条消息从哪个口子进来的(v4 账本列)。
|
|
387
|
+
*
|
|
388
|
+
* 由 `bot.dispatch(eventName, d, source)` 传:`gateway` / `webhook` /
|
|
389
|
+
* `mock`。**不在这里猜**——同一个 `GROUP_AT_MESSAGE_CREATE` 既可能来自
|
|
390
|
+
* WebSocket 网关,也可能来自 Webhook 回调,光看事件名分不出来。
|
|
391
|
+
*/
|
|
392
|
+
source: String(source ?? ''),
|
|
385
393
|
/**
|
|
386
394
|
* 内核拿到这条事件的时间。四段耗时的第一段靠它算:
|
|
387
395
|
* 官方事件到达 → 插件真正拿到,中间是内核的分发排队。
|
|
@@ -1467,6 +1475,8 @@ export function buildMessage(eventName, d, { api, cfg, outbound, session, traceI
|
|
|
1467
1475
|
target,
|
|
1468
1476
|
content: String(contentRaw ?? ''),
|
|
1469
1477
|
plugin: String(opts.plugin ?? msg.pluginId ?? ''),
|
|
1478
|
+
/** 流式绕过了 outbound.send,来源要显式给,否则账本里是空串 */
|
|
1479
|
+
source: 'plugin',
|
|
1470
1480
|
id: String(r?.id ?? streamId ?? ''),
|
|
1471
1481
|
});
|
|
1472
1482
|
} catch (e) {
|