qq-bot-roost 1.0.13 → 1.0.15
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 +10 -3
- package/config/bot.example.json +30 -0
- package/docs/AI/345/256/277/344/270/273/346/216/245/345/205/245.md +145 -0
- package/docs/DSH/346/216/245/345/205/245.md +267 -0
- package/docs/OneBot/345/205/274/345/256/271/345/261/202/350/256/276/350/256/241.md +1032 -0
- package/docs/images/bot-menu.png +0 -0
- package/docs/images/bot-switcher.png +0 -0
- package/docs/images/events.png +0 -0
- package/docs/images/group-manage.png +0 -0
- package/docs/images/logs.png +0 -0
- package/docs/images/overview.png +0 -0
- package/docs/images/plugin-dash-tab.png +0 -0
- package/docs/images/plugins-dash.png +0 -0
- package/docs/images/plugins.png +0 -0
- package/docs//345/217/221/347/211/210/346/270/205/345/215/225.md +167 -0
- package/docs//345/233/236/346/273/232/351/242/204/346/241/210.md +78 -0
- package/docs//345/256/230/346/226/271/346/216/245/345/217/243/351/231/220/345/210/266.md +375 -0
- package/docs//345/256/277/344/270/273/345/215/217/350/256/256v1.md +402 -0
- package/docs//345/270/270/350/247/201/351/227/256/351/242/230.md +559 -0
- package/docs//346/217/222/344/273/266/345/215/217/350/256/256.md +521 -0
- package/docs//346/217/222/344/273/266/345/274/200/345/217/221/350/247/204/350/214/203.md +1857 -0
- package/docs//346/235/203/351/231/220/346/250/241/345/236/213.md +237 -0
- package/docs//346/236/266/346/236/204/350/257/264/346/230/216.md +311 -0
- package/docs//347/234/237/346/234/272/350/201/224/350/260/203.md +253 -0
- package/docs//351/205/215/347/275/256/345/217/202/350/200/203.md +427 -0
- package/package.json +4 -3
- package/src/api.js +242 -77
- package/src/bot.js +93 -2
- package/src/config.js +150 -6
- package/src/endpoints.js +5 -3
- package/src/ext-deps.js +703 -0
- package/src/host/dispatch.js +125 -0
- package/src/host/index.js +395 -0
- package/src/host/media.js +462 -0
- package/src/host/methods.js +756 -0
- package/src/host/ops.js +462 -0
- package/src/host/serialize.js +79 -0
- package/src/host/server.js +397 -0
- package/src/instance.js +75 -13
- package/src/ledger.js +45 -0
- package/src/main.js +5 -1
- package/src/onebot/actions.js +524 -0
- package/src/onebot/capability.js +95 -0
- package/src/onebot/ids.js +265 -0
- package/src/onebot/index.js +410 -0
- package/src/onebot/segments.js +195 -0
- package/src/onebot/translate.js +219 -0
- package/src/onebot/voice.js +449 -0
- package/src/onebot/ws-server.js +270 -0
- package/src/plugin/loader.js +9 -0
- package/src/plugin/market.js +19 -0
- package/src/web/server.js +408 -1
- package/web/app.js +613 -0
- package/web/index.html +190 -1
- package/web/style.css +69 -0
package/src/host/ops.js
ADDED
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 宿主协议:ai-chat 等价能力 + 插件全生命周期
|
|
3
|
+
* ==========================================
|
|
4
|
+
*
|
|
5
|
+
* ai-chat 插件以前给 dsh-roost 开了四条「桥」(见它 index.js 的 registerRoute):
|
|
6
|
+
* /r/context(取邻文)、/r/delivery(查投递终态)、/r/send(主动发)、
|
|
7
|
+
* /r/status(探活)。加上它自己读的 ctx.ledger / ctx.delivery / ctx.reach /
|
|
8
|
+
* ctx.levelOf / ctx.storage,合起来就是「宿主替代 ai-chat」必须等价拿到的能力。
|
|
9
|
+
*
|
|
10
|
+
* 这里把这些能力做成协议方法,全部复用框架里已有的对象与方法,不另起一套:
|
|
11
|
+
* 账本读的还是 `R.ledger`,投递读的还是 `R.delivery.family()`,
|
|
12
|
+
* 权限算的还是 `R.roles.effective()`,插件市场用的还是 `plugin/market.js`。
|
|
13
|
+
*
|
|
14
|
+
* 注意本轮**不含**框架设置 / 运维动作的全量暴露(全局配置、更新、重启等),
|
|
15
|
+
* 按 2026-11-12 的收窄先只对齐 ai-chat;那部分留到后续版本。
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import fs from 'node:fs/promises';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import { DIRS } from '../paths.js';
|
|
21
|
+
import { saveBotConfig } from '../config.js';
|
|
22
|
+
import { FILE_TYPE } from '../api.js';
|
|
23
|
+
import {
|
|
24
|
+
fetchIndex, installPlugin, syncRepo, cleanupRepo, updatePlugins,
|
|
25
|
+
mergeWithInstalled, detectUpdates, compareVersion, isOfficialSource,
|
|
26
|
+
} from '../plugin/market.js';
|
|
27
|
+
import { resolveTrust, blockReason } from '../trust.js';
|
|
28
|
+
import { suspendPluginWatch } from '../services/plugin-watch.js';
|
|
29
|
+
import { toggleGroupPlugin } from '../plugin/groupscope.js';
|
|
30
|
+
import { scopeOf, levelName, NO_PERM } from '../roles.js';
|
|
31
|
+
|
|
32
|
+
const str = (v, d = '') => (v === undefined || v === null ? d : String(v));
|
|
33
|
+
const clamp = (v, d, max) => Math.min(max, Math.max(0, Number(v ?? d) || 0));
|
|
34
|
+
|
|
35
|
+
/** 插件 id 白名单:和面板 isSafeId 同口径,防路径穿越 */
|
|
36
|
+
const SAFE_ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
37
|
+
|
|
38
|
+
function safeId(v, err) {
|
|
39
|
+
const id = str(v).trim();
|
|
40
|
+
if (!SAFE_ID.test(id)) throw err.bad(`插件 id 不合法:${id || '(空)'}`);
|
|
41
|
+
return id;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 权限档位。数值语义来自 `src/levels.js`(0 主人 / 1 管理员 / 2 群管 / 3 助手),
|
|
46
|
+
* 字符串沿用 ai-chat 的 `bucketOfLevel()`——dsh-roost 已经在按这几个词判权限,
|
|
47
|
+
* 换名字等于静默降权。**算不准就返回 null**,让宿主按「身份不明」处理。
|
|
48
|
+
*/
|
|
49
|
+
function bucketOfLevel(lv) {
|
|
50
|
+
if (lv === null || lv === undefined || lv === '') return '';
|
|
51
|
+
const n = Number(lv);
|
|
52
|
+
if (!Number.isFinite(n) || n < 0) return '';
|
|
53
|
+
if (n <= 0) return 'owner';
|
|
54
|
+
if (n <= 1) return 'admin';
|
|
55
|
+
if (n <= 2) return 'manager';
|
|
56
|
+
if (n <= 3) return 'helper';
|
|
57
|
+
return 'member';
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 面板的 `ensurePluginInList` 是闭包里的内部函数,这里按同样规则实现一份:
|
|
62
|
+
* 只改配置里的启用名单 + 同步内存 filter,**不碰运行时加载**。
|
|
63
|
+
* 装插件时先加名单、再交给 rescan 加载,顺序反了 rescan 会认为「已经加载」
|
|
64
|
+
* 而跳过,前端就会误报安装失败。
|
|
65
|
+
*/
|
|
66
|
+
async function ensurePluginInList(R, id, enabled, err) {
|
|
67
|
+
const spec = R.cfg?.plugins ?? { mode: 'all', list: [] };
|
|
68
|
+
let mode = spec.mode ?? 'all';
|
|
69
|
+
let list = new Set(spec.list ?? []);
|
|
70
|
+
let changed = false;
|
|
71
|
+
|
|
72
|
+
if (enabled) {
|
|
73
|
+
if (mode === 'include' && !list.has(id)) { list.add(id); changed = true; }
|
|
74
|
+
else if (mode === 'exclude' && list.has(id)) { list.delete(id); changed = true; }
|
|
75
|
+
} else if (mode === 'include' && list.has(id)) { list.delete(id); changed = true; }
|
|
76
|
+
else if (mode === 'exclude' && !list.has(id)) { list.add(id); changed = true; }
|
|
77
|
+
else if (mode === 'all') { mode = 'exclude'; list = new Set([id]); changed = true; }
|
|
78
|
+
|
|
79
|
+
if (!changed) return false;
|
|
80
|
+
R.cfg.plugins = { ...spec, mode, list: [...list] };
|
|
81
|
+
/** 动态 import:bot.js → host/index.js → methods.js → ops.js 是一条环,
|
|
82
|
+
* 顶层静态导入会拿到未初始化的绑定。调用时再取,模块早已就绪。 */
|
|
83
|
+
const { pluginFilterOf } = await import('../bot.js');
|
|
84
|
+
if (R.plugins) R.plugins.filter = pluginFilterOf(R.cfg.plugins);
|
|
85
|
+
await saveBotConfig(R.id, R.cfg);
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** 市场写操作的共同前置:最新索引 + 信任闸 */
|
|
90
|
+
async function freshIndex(R, err) {
|
|
91
|
+
const src = R.globalCfg?.plugins?.marketUrl || undefined;
|
|
92
|
+
const idx = await fetchIndex(src, { trust: resolveTrust(R.globalCfg ?? {}), maxAge: 0 });
|
|
93
|
+
return { src, idx };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function trustGate(R, idx, src, id, err) {
|
|
97
|
+
const official = isOfficialSource(src, R.globalCfg ?? {});
|
|
98
|
+
const why = blockReason(
|
|
99
|
+
resolveTrust(R.globalCfg ?? {}),
|
|
100
|
+
idx?._trust?.status || 'unavailable',
|
|
101
|
+
id,
|
|
102
|
+
{ official },
|
|
103
|
+
);
|
|
104
|
+
if (why) throw err.forbidden(why);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* @param {(name,scope,desc,run)=>void} def
|
|
109
|
+
* @param {object} ctx
|
|
110
|
+
* @param {object} ctx.R BotRuntime
|
|
111
|
+
* @param {object} ctx.err { bad, notFound, notReady, forbidden }
|
|
112
|
+
* @param {(s:string)=>void} [ctx.log]
|
|
113
|
+
*/
|
|
114
|
+
export function registerOps(def, { R, err, log = () => {} }) {
|
|
115
|
+
const plugins = () => {
|
|
116
|
+
if (!R.plugins) throw err.notReady('插件管理器未就绪');
|
|
117
|
+
return R.plugins;
|
|
118
|
+
};
|
|
119
|
+
const ledger = () => {
|
|
120
|
+
if (!R.ledger) throw err.notReady('事件账本未就绪');
|
|
121
|
+
return R.ledger;
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
/* ---------------- ai-chat 的四条桥 ---------------- */
|
|
125
|
+
|
|
126
|
+
def('ledger.context', 'read', '按 eventId 取原文与前后邻文(ai-chat /r/context 等价)', async (p) => {
|
|
127
|
+
const aroundId = str(p.aroundId).trim();
|
|
128
|
+
if (!aroundId) throw err.bad('要给 aroundId(事件账本里的 id)');
|
|
129
|
+
const L = ledger();
|
|
130
|
+
const row = L.get(aroundId);
|
|
131
|
+
if (!row) {
|
|
132
|
+
return {
|
|
133
|
+
ok: false, gone: true,
|
|
134
|
+
message: '找不到这条事件——可能超过保留期被滚动删了,证据快照还在记忆里',
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
const items = L.timeline({
|
|
138
|
+
chatId: row.chat_id,
|
|
139
|
+
anchorSeq: row.seq,
|
|
140
|
+
before: clamp(p.before, 2, 10),
|
|
141
|
+
after: clamp(p.after, 2, 10),
|
|
142
|
+
});
|
|
143
|
+
return {
|
|
144
|
+
ok: true,
|
|
145
|
+
anchor: { id: row.id, seq: row.seq, at: row.at, chatId: row.chat_id },
|
|
146
|
+
items,
|
|
147
|
+
};
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
def('ledger.timeline', 'read', '按会话与 seq 取前后文', async (p) => ({
|
|
151
|
+
items: ledger().timeline({
|
|
152
|
+
chatId: str(p.chatId),
|
|
153
|
+
anchorSeq: Number(p.anchorSeq) || 0,
|
|
154
|
+
before: clamp(p.before, 2, 10),
|
|
155
|
+
after: clamp(p.after, 2, 10),
|
|
156
|
+
}),
|
|
157
|
+
}));
|
|
158
|
+
|
|
159
|
+
def('ledger.stats', 'read', '事件账本统计', async () => await ledger().stats());
|
|
160
|
+
|
|
161
|
+
def('delivery.get', 'read', '按 requestId 查投递终态,多分块自动聚合(ai-chat /r/delivery 等价)', async (p) => {
|
|
162
|
+
const rid = str(p.requestId).trim();
|
|
163
|
+
if (!rid) throw err.bad('要给 requestId');
|
|
164
|
+
const D = R.delivery;
|
|
165
|
+
if (!D) throw err.notReady('投递账本未就绪');
|
|
166
|
+
const fam = D.family?.(rid) ?? null;
|
|
167
|
+
if (fam) {
|
|
168
|
+
return {
|
|
169
|
+
ok: true, state: fam.state, msgId: fam.msgId, code: fam.code,
|
|
170
|
+
attempts: fam.attempts, at: fam.at, parts: fam.parts,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/** 老框架的 delivery 没有 family(),退回精确查一条 */
|
|
174
|
+
const row = D.get?.(rid);
|
|
175
|
+
if (!row) {
|
|
176
|
+
return { ok: false, gone: true, message: '没有这条投递记录(可能没开账本,或者 id 不对)' };
|
|
177
|
+
}
|
|
178
|
+
return {
|
|
179
|
+
ok: true, state: row.state, msgId: row.msg_id || '', code: row.code || '',
|
|
180
|
+
attempts: Number(row.attempts || 0),
|
|
181
|
+
at: Number(row.settled_at || row.created_at || 0), parts: 1,
|
|
182
|
+
};
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
def('delivery.recent', 'read', '最近投递记录', async (p) => ({
|
|
186
|
+
items: R.delivery?.recent?.({ limit: clamp(p.limit, 50, 200), state: str(p.state) }) ?? [],
|
|
187
|
+
stats: R.delivery?.stats?.() ?? { available: false },
|
|
188
|
+
}));
|
|
189
|
+
|
|
190
|
+
def('roles.resolve', 'read', '算发送者权限档位 bucket/level/role(ai-chat senderInfo 等价)', async (p) => {
|
|
191
|
+
const userId = str(p.userId).trim();
|
|
192
|
+
if (!userId) throw err.bad('要给 userId(openid)');
|
|
193
|
+
const owners = Array.isArray(R.cfg?.owners) ? R.cfg.owners : [];
|
|
194
|
+
const msg = { userId, kind: p.kind === 'group' ? 'group' : 'c2c',
|
|
195
|
+
chatId: str(p.chatId), groupId: str(p.groupId) || str(p.chatId) };
|
|
196
|
+
try {
|
|
197
|
+
if (owners.includes(userId)) {
|
|
198
|
+
return { userId, bucket: 'owner', level: 0, role: levelName(0) };
|
|
199
|
+
}
|
|
200
|
+
const lv = R.roles
|
|
201
|
+
? await R.roles.effective(scopeOf(msg), userId, { owners })
|
|
202
|
+
: NO_PERM;
|
|
203
|
+
const bucket = bucketOfLevel(lv);
|
|
204
|
+
if (!bucket) return { userId, bucket: null, level: null, role: null };
|
|
205
|
+
return { userId, bucket, level: lv, role: levelName(lv) };
|
|
206
|
+
} catch (e) {
|
|
207
|
+
log(`权限查询失败(${userId}):${e?.message ?? e}`);
|
|
208
|
+
return { userId, bucket: null, level: null, role: null };
|
|
209
|
+
}
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
def('reach.get', 'read', '查这个会话能不能主动推送(官方没有查询接口,靠事件维护)', async (p) => {
|
|
213
|
+
const target = str(p.target).trim();
|
|
214
|
+
if (!target) throw err.bad('要给 target');
|
|
215
|
+
if (!R.reach) throw err.notReady('可达性表未就绪');
|
|
216
|
+
const kind = p.kind === 'group' ? 'group' : 'c2c';
|
|
217
|
+
const v = kind === 'group'
|
|
218
|
+
? await R.reach.canGroupPush?.(target)
|
|
219
|
+
: await R.reach.canC2C?.(target);
|
|
220
|
+
return { kind, target, ...(v ?? { verdict: 'unknown' }) };
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
def('reach.note', 'manage', '发送成功/失败后回写可达性(ai-chat /r/send 等价)', async (p) => {
|
|
224
|
+
const target = str(p.target).trim();
|
|
225
|
+
if (!target) throw err.bad('要给 target');
|
|
226
|
+
if (!R.reach) throw err.notReady('可达性表未就绪');
|
|
227
|
+
if (p.ok === true) {
|
|
228
|
+
await R.reach.noteSendOk?.({ openid: target });
|
|
229
|
+
} else {
|
|
230
|
+
await R.reach.noteSendError?.({ openid: target, qqCode: Number(p.qqCode) || 0 });
|
|
231
|
+
}
|
|
232
|
+
return { ok: true };
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
def('gate.silence', 'message', '让某个会话安静一段时间(ai-chat <<silence>> 等价)', async (p) => {
|
|
236
|
+
const chatId = str(p.chatId).trim();
|
|
237
|
+
const ms = Number(p.ms) || 0;
|
|
238
|
+
if (!chatId || ms <= 0) throw err.bad('要给 chatId 和正数 ms');
|
|
239
|
+
if (!R.gate) throw err.notReady('暂停闸未就绪');
|
|
240
|
+
return await R.gate.setSilence(chatId, Math.min(ms, 30 * 86_400_000), {
|
|
241
|
+
by: 'host', reason: str(p.reason).slice(0, 200),
|
|
242
|
+
});
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
/* ---------------- 插件存档 / 配置 / 分群开关 ---------------- */
|
|
246
|
+
|
|
247
|
+
def('plugin.data.get', 'read', '读插件存档(ai-chat ctx.storage 等价)', async (p) => {
|
|
248
|
+
const item = plugins().loaded.get(safeId(p.id, err));
|
|
249
|
+
if (!item) throw err.notFound('插件没加载');
|
|
250
|
+
const st = item.ctx?.storage;
|
|
251
|
+
if (!st) throw err.notReady('这个插件没有存档(外部子进程插件可能没有 ctx)');
|
|
252
|
+
const all = await st.all();
|
|
253
|
+
if (p.key !== undefined) return { key: str(p.key), value: all[str(p.key)] ?? null };
|
|
254
|
+
return { data: all };
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
def('plugin.data.set', 'manage', '写一条插件存档', async (p) => {
|
|
258
|
+
const id = safeId(p.id, err);
|
|
259
|
+
const key = str(p.key).trim();
|
|
260
|
+
if (!key) throw err.bad('要给 key');
|
|
261
|
+
return { ok: true, ...(await plugins().setData(id, key, p.value)) };
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
def('plugin.data.delete', 'manage', '删一条插件存档', async (p) => {
|
|
265
|
+
const id = safeId(p.id, err);
|
|
266
|
+
const key = str(p.key).trim();
|
|
267
|
+
if (!key) throw err.bad('要给 key');
|
|
268
|
+
return { ok: true, ...(await plugins().deleteData(id, key)) };
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
def('plugin.data.clear', 'manage', '清空某插件全部存档', async (p) => {
|
|
272
|
+
if (p.confirm !== true) throw err.bad('清空存档不可恢复,请显式传 confirm: true');
|
|
273
|
+
return { ok: true, ...(await plugins().clearData(safeId(p.id, err))) };
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
def('plugin.config.reset', 'manage', '恢复插件出厂配置', async (p) => {
|
|
277
|
+
if (p.confirm !== true) throw err.bad('恢复出厂会清掉 API Key 等配置,请显式传 confirm: true');
|
|
278
|
+
return { config: await plugins().resetConfig(safeId(p.id, err)) };
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
def('plugin.groups.get', 'read', '某个插件在各群的启用情况', async (p) => {
|
|
282
|
+
const pid = safeId(p.id, err);
|
|
283
|
+
const spec = R.cfg?.plugins ?? { mode: 'all', list: [] };
|
|
284
|
+
const groups = await (R.groups?.list?.() ?? Promise.resolve([]));
|
|
285
|
+
await R.fetchGroupNames?.(groups.map((g) => g.groupOpenid)).catch(() => {});
|
|
286
|
+
return {
|
|
287
|
+
pluginId: pid,
|
|
288
|
+
global: { mode: spec.mode ?? 'all', list: spec.list ?? [] },
|
|
289
|
+
groups: groups.map((g) => ({
|
|
290
|
+
chatId: g.groupOpenid,
|
|
291
|
+
name: R.groupNames?.get?.(g.groupOpenid)?.name ?? '',
|
|
292
|
+
enabled: true,
|
|
293
|
+
})),
|
|
294
|
+
groupsSpec: spec.groups ?? {},
|
|
295
|
+
};
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
def('plugin.groups.set', 'manage', '在某个群启用/停用某插件', async (p) => {
|
|
299
|
+
const pid = safeId(p.id, err);
|
|
300
|
+
const chatId = str(p.chatId).trim();
|
|
301
|
+
if (!chatId) throw err.bad('要给 chatId');
|
|
302
|
+
const spec = R.cfg?.plugins ?? { mode: 'all', list: [] };
|
|
303
|
+
const groupsCfg = toggleGroupPlugin(spec, chatId, pid, p.enabled === true);
|
|
304
|
+
R.cfg.plugins = { ...spec, groups: groupsCfg };
|
|
305
|
+
await saveBotConfig(R.id, R.cfg);
|
|
306
|
+
return { ok: true, chatId, pluginId: pid, groups: groupsCfg };
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
/* ---------------- 插件市场 / 全生命周期 ---------------- */
|
|
310
|
+
|
|
311
|
+
def('plugin.market', 'read', '插件市场索引 + 已装标记 + 可更新列表', async (p) => {
|
|
312
|
+
const src = str(p.source) || R.globalCfg?.plugins?.marketUrl || undefined;
|
|
313
|
+
const idx = await fetchIndex(src, { trust: resolveTrust(R.globalCfg ?? {}) });
|
|
314
|
+
const installed = new Set(plugins().loaded.keys());
|
|
315
|
+
try {
|
|
316
|
+
for (const d of await fs.readdir(DIRS.plugins, { withFileTypes: true })) {
|
|
317
|
+
if (d.isDirectory()) installed.add(d.name);
|
|
318
|
+
}
|
|
319
|
+
} catch { /* 目录还没有就算了 */ }
|
|
320
|
+
const localVers = await plugins().localVersions();
|
|
321
|
+
return {
|
|
322
|
+
repo: idx.repo, updated: idx.updated, source: src || 'default',
|
|
323
|
+
plugins: mergeWithInstalled(idx.plugins, installed),
|
|
324
|
+
updates: detectUpdates(idx.plugins, localVers).map((u) => ({
|
|
325
|
+
id: u.id, current: u.current, latest: u.latest,
|
|
326
|
+
})),
|
|
327
|
+
localVersions: localVers,
|
|
328
|
+
trust: idx?._trust?.status || 'unavailable',
|
|
329
|
+
stale: idx.stale === true, staleAge: idx.staleAge || '',
|
|
330
|
+
};
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
def('plugin.versions', 'read', '本地已装插件版本(以磁盘为准)', async () => ({
|
|
334
|
+
versions: await plugins().localVersions(),
|
|
335
|
+
}));
|
|
336
|
+
|
|
337
|
+
def('plugin.updates', 'read', '检查哪些插件有新版', async () => {
|
|
338
|
+
const { idx } = await freshIndex(R, err);
|
|
339
|
+
const localVers = await plugins().localVersions();
|
|
340
|
+
return { updates: detectUpdates(idx.plugins, localVers), stale: idx.stale === true };
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
def('plugin.install', 'manage', '从市场安装插件(装完自动 rescan 加载)', async (p) => {
|
|
344
|
+
const id = safeId(p.id, err);
|
|
345
|
+
const { src, idx } = await freshIndex(R, err);
|
|
346
|
+
const entry = idx.plugins.find((x) => x.id === id);
|
|
347
|
+
if (!entry) throw err.notFound(`市场里没有 ${id}`);
|
|
348
|
+
trustGate(R, idx, src, id, err);
|
|
349
|
+
|
|
350
|
+
/** 下载解包期间挂起热重载:文件是一个个复制进来的,中途会读到半个插件 */
|
|
351
|
+
suspendPluginWatch(30_000);
|
|
352
|
+
try {
|
|
353
|
+
const r = await installPlugin({
|
|
354
|
+
entry,
|
|
355
|
+
pluginsDir: DIRS.plugins,
|
|
356
|
+
repo: idx.repo,
|
|
357
|
+
branch: idx.branch || 'main',
|
|
358
|
+
sha256: idx?.archive?.sha256 ?? idx?.sha256 ?? null,
|
|
359
|
+
exists: (pid) => plugins().loaded.has(pid),
|
|
360
|
+
});
|
|
361
|
+
await ensurePluginInList(R, r.id, true, err);
|
|
362
|
+
const scanned = await plugins().rescan();
|
|
363
|
+
return { ok: true, id: r.id, ...scanned };
|
|
364
|
+
} finally {
|
|
365
|
+
suspendPluginWatch(1000);
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
def('plugin.remove', 'manage', '卸载插件(删目录,保留数据目录;需 confirm)', async (p) => {
|
|
370
|
+
if (p.confirm !== true) throw err.bad('卸载会删除插件目录,请显式传 confirm: true');
|
|
371
|
+
const id = safeId(p.id, err);
|
|
372
|
+
const base = path.resolve(DIRS.plugins);
|
|
373
|
+
const dir = path.resolve(base, id);
|
|
374
|
+
/** 路径穿越三重校验:id 白名单 + resolve 后必须是 base 的直接子目录 */
|
|
375
|
+
if (!dir.startsWith(base + path.sep) || path.dirname(dir) !== base) {
|
|
376
|
+
throw err.bad('路径越界,已拒绝');
|
|
377
|
+
}
|
|
378
|
+
const st = await fs.stat(dir).catch(() => null);
|
|
379
|
+
if (!st?.isDirectory()) throw err.notFound(`插件 ${id} 没装(${dir})`);
|
|
380
|
+
|
|
381
|
+
suspendPluginWatch(15_000);
|
|
382
|
+
try {
|
|
383
|
+
if (plugins().loaded.has(id)) await plugins().unload(id).catch(() => {});
|
|
384
|
+
await ensurePluginInList(R, id, false, err).catch(() => {});
|
|
385
|
+
await fs.rm(dir, { recursive: true, force: true });
|
|
386
|
+
await plugins().forget(id).catch(() => {});
|
|
387
|
+
const scanned = await plugins().rescan();
|
|
388
|
+
log(`已卸载插件 ${id}(数据目录保留,重装可继续用):${dir}`);
|
|
389
|
+
return { ok: true, id, removedPath: dir, ...scanned };
|
|
390
|
+
} finally {
|
|
391
|
+
suspendPluginWatch(1000);
|
|
392
|
+
}
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
def('plugin.update', 'manage', '更新单个插件到市场最新版', async (p) => {
|
|
396
|
+
const id = safeId(p.id, err);
|
|
397
|
+
let repo = null;
|
|
398
|
+
try {
|
|
399
|
+
const { src, idx } = await freshIndex(R, err);
|
|
400
|
+
const entry = idx.plugins.find((x) => x.id === id);
|
|
401
|
+
if (!entry) throw err.notFound(`市场里没有 ${id}`);
|
|
402
|
+
trustGate(R, idx, src, id, err);
|
|
403
|
+
const localVers = await plugins().localVersions();
|
|
404
|
+
const cur = localVers[id];
|
|
405
|
+
if (!cur) throw err.bad(`本地没装 ${id},先用 plugin.install`);
|
|
406
|
+
if (compareVersion(cur, entry.version) >= 0) {
|
|
407
|
+
throw err.bad(`${id} 已经是 ${cur},没有新版`);
|
|
408
|
+
}
|
|
409
|
+
repo = await syncRepo({
|
|
410
|
+
repo: idx.repo, branch: idx.branch || 'main', indexUrl: src,
|
|
411
|
+
only: [`plugins/${id}/`], index: idx,
|
|
412
|
+
});
|
|
413
|
+
const r = await updatePlugins({
|
|
414
|
+
tmp: repo.tmp, index: repo.index, pluginsDir: DIRS.plugins,
|
|
415
|
+
ids: [id], localVersions: localVers,
|
|
416
|
+
});
|
|
417
|
+
if (r.failed.length) throw err.bad(r.failed[0].error);
|
|
418
|
+
if (!r.updated.length) throw err.bad(`${id} 没有可用的更新`);
|
|
419
|
+
await plugins().reload(id).catch((e) => log(`插件 ${id} 更新后重载失败:${e.message}`));
|
|
420
|
+
const scanned = await plugins().rescan();
|
|
421
|
+
return { ok: true, from: r.updated[0].from, to: r.updated[0].to, ...scanned };
|
|
422
|
+
} finally {
|
|
423
|
+
await cleanupRepo(repo?.tmp);
|
|
424
|
+
}
|
|
425
|
+
});
|
|
426
|
+
|
|
427
|
+
def('plugin.update.all', 'manage', '一键更新所有有新版的插件', async () => {
|
|
428
|
+
let repo = null;
|
|
429
|
+
try {
|
|
430
|
+
const src = R.globalCfg?.plugins?.marketUrl || undefined;
|
|
431
|
+
repo = await syncRepo({ indexUrl: src });
|
|
432
|
+
const localVers = await plugins().localVersions();
|
|
433
|
+
const r = await updatePlugins({
|
|
434
|
+
tmp: repo.tmp, index: repo.index,
|
|
435
|
+
pluginsDir: DIRS.plugins, localVersions: localVers,
|
|
436
|
+
});
|
|
437
|
+
for (const u of r.updated) {
|
|
438
|
+
await plugins().reload(u.id).catch((e) => log(`插件 ${u.id} 重载失败:${e.message}`));
|
|
439
|
+
}
|
|
440
|
+
const scanned = await plugins().rescan();
|
|
441
|
+
return { ok: true, ...r, ...scanned };
|
|
442
|
+
} finally {
|
|
443
|
+
await cleanupRepo(repo?.tmp);
|
|
444
|
+
}
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
def('plugin.rescan', 'manage', '重扫插件目录,加载新增 / 卸载已删', async () => ({
|
|
448
|
+
ok: true, ...(await plugins().rescan()), plugins: plugins().list(),
|
|
449
|
+
}));
|
|
450
|
+
|
|
451
|
+
def('plugin.load', 'manage', '加载单个插件', async (p) => ({
|
|
452
|
+
ok: true, result: await plugins().load(safeId(p.id, err)),
|
|
453
|
+
}));
|
|
454
|
+
|
|
455
|
+
def('plugin.unload', 'manage', '卸载单个插件的运行时(不删文件)', async (p) => ({
|
|
456
|
+
ok: true, result: await plugins().unload(safeId(p.id, err)),
|
|
457
|
+
}));
|
|
458
|
+
|
|
459
|
+
def('plugin.forget', 'manage', '清掉插件状态里的残留开关记录', async (p) => ({
|
|
460
|
+
ok: true, result: await plugins().forget(safeId(p.id, err)),
|
|
461
|
+
}));
|
|
462
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 事件序列化:内核 Message → 宿主协议事件
|
|
3
|
+
* ======================================
|
|
4
|
+
*
|
|
5
|
+
* **不做 OneBot 翻译**,字段保持框架里的名字和含义。
|
|
6
|
+
* 特别是 openid / uin:没绑就是空串,绝不造一个「看起来像 QQ 号」的合成号——
|
|
7
|
+
* 客户端拿合成号去查记忆,查不到还不会报错,只会「像换了个人」。
|
|
8
|
+
*
|
|
9
|
+
* `msg.raw`(平台原始事件体)不进事件流:它带一堆内部字段、体积不可控,
|
|
10
|
+
* 需要时用 `msg.get` 按 id 查账本。这里只留正文原文 `rawContent`。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @param {object} msg `buildMessage()` 的产物
|
|
15
|
+
* @param {object} [opt]
|
|
16
|
+
* @param {string} [opt.groupName] 群名缓存里查到的名字,查不到就空
|
|
17
|
+
*/
|
|
18
|
+
export function serializeMessage(msg, { groupName = '' } = {}) {
|
|
19
|
+
if (!msg || typeof msg !== 'object') return null;
|
|
20
|
+
return {
|
|
21
|
+
at: Number(msg.receivedAt) || Date.now(),
|
|
22
|
+
chat: {
|
|
23
|
+
kind: msg.kind ?? 'unknown',
|
|
24
|
+
chatId: msg.chatId ?? '',
|
|
25
|
+
groupId: msg.groupId ?? '',
|
|
26
|
+
groupUin: msg.groupUin ?? '',
|
|
27
|
+
groupIdentityId: msg.groupIdentityId ?? '',
|
|
28
|
+
groupAliases: Array.isArray(msg.groupAliases) ? msg.groupAliases : [],
|
|
29
|
+
name: groupName,
|
|
30
|
+
},
|
|
31
|
+
sender: {
|
|
32
|
+
openid: msg.userId ?? '',
|
|
33
|
+
uin: msg.uin ?? '',
|
|
34
|
+
identityId: msg.identityId ?? '',
|
|
35
|
+
aliases: Array.isArray(msg.userAliases) ? msg.userAliases : [],
|
|
36
|
+
name: msg.userName ?? '',
|
|
37
|
+
isBot: msg.raw?.author?.bot === true,
|
|
38
|
+
},
|
|
39
|
+
msgId: msg.id ?? '',
|
|
40
|
+
/**
|
|
41
|
+
* 事件账本里的 id。**和 `msgId` 不是一回事**:msgId 用来被动回复,
|
|
42
|
+
* eventId 用来回查原文(`ledger.context` / `msg.get` 的入参都是它,
|
|
43
|
+
* `events` 表的主键就是 eventId)。
|
|
44
|
+
*
|
|
45
|
+
* 不开账本时是空串——那时也确实没有东西可回查,不是丢数据。
|
|
46
|
+
*/
|
|
47
|
+
eventId: msg.eventId ?? '',
|
|
48
|
+
traceId: msg.traceId ?? '',
|
|
49
|
+
event: msg.event ?? '',
|
|
50
|
+
eventMeta: msg.eventMeta ?? null,
|
|
51
|
+
content: msg.content ?? '',
|
|
52
|
+
/** 未剥 @、未 trim 的原文,客户端想自己解析时用它 */
|
|
53
|
+
rawContent: String(msg.raw?.content ?? ''),
|
|
54
|
+
addressed: Boolean(msg.addressed),
|
|
55
|
+
mentioned: Boolean(msg.mentioned),
|
|
56
|
+
isCommand: Boolean(msg.isCommand),
|
|
57
|
+
command: msg.command ?? '',
|
|
58
|
+
args: Array.isArray(msg.args) ? msg.args : [],
|
|
59
|
+
mentions: Array.isArray(msg.mentions) ? msg.mentions : [],
|
|
60
|
+
allMentions: Array.isArray(msg.allMentions) ? msg.allMentions : [],
|
|
61
|
+
attachments: Array.isArray(msg.attachments) ? msg.attachments : [],
|
|
62
|
+
scene: msg.scene ?? null,
|
|
63
|
+
ark: msg.ark ?? null,
|
|
64
|
+
elements: msg.elements ?? null,
|
|
65
|
+
/**
|
|
66
|
+
* 被引用的原文。**不能只给 `replyTo`**:那个是 message_id,客户端拿它
|
|
67
|
+
* 拼不出「引用了哪句话」,只能看到一个 id。引用回复的正文在这里。
|
|
68
|
+
*
|
|
69
|
+
* 拿不到时是空串(QQ 有些场景不回推被引用的内容),不是错误。
|
|
70
|
+
*/
|
|
71
|
+
quoted: msg.quoted ?? '',
|
|
72
|
+
replyTo: msg.raw?.message_reference?.message_id ?? null,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 非消息事件(入群、退群、加好友…)原样带 out,不猜结构 */
|
|
77
|
+
export function serializeNotice(event, data) {
|
|
78
|
+
return { at: Date.now(), event: String(event ?? ''), data: data ?? null };
|
|
79
|
+
}
|