qq-bot-roost 1.1.19 → 1.2.0
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/docs//345/256/277/344/270/273/345/215/217/350/256/256v1.md +77 -3
- package/package.json +3 -3
- package/src/bot.js +26 -17
- package/src/command-perm.js +47 -0
- package/src/config-reset.js +186 -0
- package/src/config.js +8 -2
- package/src/host/ext-bridge.js +257 -34
- package/src/host/inbound-forward.js +11 -1
- package/src/host/index.js +194 -7
- package/src/host/methods.js +12 -3
- package/src/main.js +42 -7
- package/src/plugin/context.js +27 -1
- package/src/web/key-strength.js +94 -0
- package/src/web/server.js +247 -13
- package/web/app.js +95 -16
- package/web/index.html +13 -4
- package/web/login.js +68 -0
package/src/host/ext-bridge.js
CHANGED
|
@@ -19,6 +19,19 @@
|
|
|
19
19
|
* 为什么扩展能力不投影成 `tool.*`:`tool.*` 的 scope 是 `message`,谁拿到
|
|
20
20
|
* 协议令牌都能调;而扩展动作可能带写操作(发消息、评论),应当只在框架
|
|
21
21
|
* 插件明确调用时才发生,且由 DSH 自己按 `ui.actions` 白名单把着。
|
|
22
|
+
*
|
|
23
|
+
* ── 命令(1.2.0 起)─────────────────────────────────────────────────
|
|
24
|
+
*
|
|
25
|
+
* 同一份 `ext.register` 还可以上报 `commands`:外接客户端(宿主本体)和它装的
|
|
26
|
+
* 扩展,都能在框架侧**注册聊天命令**,命令名与其他插件命令一样进 `/help`。
|
|
27
|
+
* 触发时框架推 `ext.command.request`,客户端用 RPC `ext.command.reply` 回执:
|
|
28
|
+
*
|
|
29
|
+
* · 回执带 `reply` → 框架替它发(走 `msg.reply`,带引用,限频/窗口都受管);
|
|
30
|
+
* · 不回 `reply` → 认为客户端自己用 `msg.send` 发过了,框架不再补一句。
|
|
31
|
+
*
|
|
32
|
+
* 注册是**幂等重建**:每次 register 先按伪插件 id 清空旧命令再装新的,
|
|
33
|
+
* 所以「扩展卸了但命令还在」不会发生。重名不覆盖——`addCommand` 抛错就
|
|
34
|
+
* 跳过,并把这批冲突放进回执的 `rejected`,客户端记日志即可。
|
|
22
35
|
*/
|
|
23
36
|
|
|
24
37
|
import { HostError } from './methods.js';
|
|
@@ -26,12 +39,95 @@ import { HostError } from './methods.js';
|
|
|
26
39
|
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
27
40
|
const MAX_PENDING = 32;
|
|
28
41
|
const MAX_PAYLOAD_KEYS = 40;
|
|
42
|
+
/** 命令回执正文上限:QQ 单条本来也放不下更多,截断比报错友好 */
|
|
43
|
+
const MAX_REPLY_CHARS = 2000;
|
|
44
|
+
/** 一次上报的命令总数上限(宿主 + 全部扩展),防客户端刷清单 */
|
|
45
|
+
const MAX_COMMANDS = 60;
|
|
46
|
+
/** 每条命令的别名上限 */
|
|
47
|
+
const MAX_ALIASES = 4;
|
|
48
|
+
/** 命令名:字母(含中文)/数字/下划线/连字符,最长 16;与原生命令表口径一致 */
|
|
49
|
+
const CMD_NAME_RE = /^[\p{L}\p{N}_-]{1,16}$/u;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 命令表里的内部 id 统一加 `ext:` 前缀。
|
|
53
|
+
*
|
|
54
|
+
* 以前写死 `__host`,它会一路漏进 `/help 插件` 的列表里,用户看到的是
|
|
55
|
+
* 「__host DSH」——一个谁也认不出的内部代号;后来改成 `__<自报名>`,
|
|
56
|
+
* 仍然带着两个下划线,像内部变量。现在宿主本体用 `ext:<自报名>`
|
|
57
|
+
* (默认 `ext:dsh`),扩展用 `ext:<extId>`。
|
|
58
|
+
*
|
|
59
|
+
* 前缀的作用只有一个:**它是外接协议方,不是插件**。分群「只启用列表」
|
|
60
|
+
* 对它放行(见 `bot.js` 的 `pluginAllowedIn`),`/help 插件` 靠它筛掉,
|
|
61
|
+
* `/help 协议` 靠它单列一栏。`:` 在 Windows 目录名里非法,所以永远不会
|
|
62
|
+
* 和真实插件 id 撞。
|
|
63
|
+
*
|
|
64
|
+
* 后续接别的程序时,各自在 `host.name` 里报不同名字就各占一个命名空间,
|
|
65
|
+
* 不用抢固定 id;真正的多连接并行还需要协议层给每条连接一个身份
|
|
66
|
+
* (`ext.register` 目前是一条连接一次全量上报)。
|
|
67
|
+
*/
|
|
68
|
+
function virtualPluginId(name) {
|
|
69
|
+
const slug = String(name ?? '')
|
|
70
|
+
.trim()
|
|
71
|
+
.toLowerCase()
|
|
72
|
+
.replace(/[^\p{L}\p{N}_-]+/gu, '-')
|
|
73
|
+
.replace(/^-+|-+$/g, '')
|
|
74
|
+
.slice(0, 32);
|
|
75
|
+
return `ext:${slug || 'dsh'}`;
|
|
76
|
+
}
|
|
29
77
|
|
|
30
|
-
|
|
31
|
-
|
|
78
|
+
/**
|
|
79
|
+
* 把客户端上报的命令条目洗成内部结构。
|
|
80
|
+
*
|
|
81
|
+
* target = 'host' 表示宿主本体(`ext:<host.name>`),'ext' 表示某个扩展
|
|
82
|
+
* (`ext:<id>`)。名字不合法直接丢——命令表是全局命名空间,
|
|
83
|
+
* 不能让一个畸形条目把别的插件注册流程带崩。
|
|
84
|
+
*/
|
|
85
|
+
function normalizeCommands(list, { target, extId = '', pluginName }) {
|
|
86
|
+
const out = [];
|
|
87
|
+
const name = String(pluginName ?? '').trim() || (target === 'host' ? 'dsh' : extId);
|
|
88
|
+
const pluginId = target === 'host' ? virtualPluginId(name) : `ext:${extId}`;
|
|
89
|
+
for (const c of Array.isArray(list) ? list : []) {
|
|
90
|
+
if (!c || typeof c !== 'object') continue;
|
|
91
|
+
const cmd = String(c.name ?? '').trim().toLowerCase();
|
|
92
|
+
if (!CMD_NAME_RE.test(cmd)) continue;
|
|
93
|
+
const aliases = (Array.isArray(c.aliases) ? c.aliases : [])
|
|
94
|
+
.map((a) => String(a ?? '').trim().toLowerCase())
|
|
95
|
+
.filter((a) => a && a !== cmd && CMD_NAME_RE.test(a))
|
|
96
|
+
.slice(0, MAX_ALIASES);
|
|
97
|
+
out.push({
|
|
98
|
+
target,
|
|
99
|
+
extId,
|
|
100
|
+
pluginId,
|
|
101
|
+
pluginName: name.slice(0, 40),
|
|
102
|
+
name: cmd,
|
|
103
|
+
aliases,
|
|
104
|
+
desc: String(c.desc ?? '').slice(0, 60),
|
|
105
|
+
usage: String(c.usage ?? '').slice(0, 120),
|
|
106
|
+
admin: c.admin === true,
|
|
107
|
+
globalAdmin: c.globalAdmin === true,
|
|
108
|
+
ownerOnly: c.ownerOnly === true,
|
|
109
|
+
hidden: c.hidden === true,
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
return out;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function createExtBridge({
|
|
116
|
+
pushEvent = () => {},
|
|
117
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
118
|
+
log = () => {},
|
|
119
|
+
/**
|
|
120
|
+
* 把命令装进 registry 并返回冲突列表。桥本身不碰 registry(纯逻辑好测),
|
|
121
|
+
* 由 HostBridge 注入;不注入时命令只进清单、不生效(例如单测里没有 runtime)。
|
|
122
|
+
*/
|
|
123
|
+
installCommands = null,
|
|
124
|
+
} = {}) {
|
|
125
|
+
/** requestId -> { resolve, reject, timer, at } —— 扩展调用与命令共用一张表 */
|
|
32
126
|
const pending = new Map();
|
|
33
|
-
/** DSH 上报的扩展能力清单:{ extId, actions:[{id,label}] }[] */
|
|
127
|
+
/** DSH 上报的扩展能力清单:{ extId, name, actions:[{id,label}] }[] */
|
|
34
128
|
let catalog = [];
|
|
129
|
+
/** 当前生效的命令(内部结构),list() 会给副本 */
|
|
130
|
+
let commands = [];
|
|
35
131
|
let catalogAt = 0;
|
|
36
132
|
let seq = 0;
|
|
37
133
|
|
|
@@ -41,26 +137,12 @@ export function createExtBridge({ pushEvent = () => {}, timeoutMs = DEFAULT_TIME
|
|
|
41
137
|
p.reject(e);
|
|
42
138
|
}
|
|
43
139
|
|
|
44
|
-
/**
|
|
45
|
-
|
|
46
|
-
*
|
|
47
|
-
* @returns {Promise<any>} DSH 回执里的 result
|
|
48
|
-
*/
|
|
49
|
-
async function call({ extId = '', action = '', payload = null, chat = '' } = {}) {
|
|
50
|
-
const id = String(extId ?? '').trim();
|
|
51
|
-
const act = String(action ?? '').trim();
|
|
52
|
-
if (!id || !act) throw new HostError('BAD_PARAMS', '要给 extId 与 action', 400);
|
|
140
|
+
/** 发一条要求回执的请求,超时/断线都能失败 */
|
|
141
|
+
function request(event, data, prefix, timeoutMessage) {
|
|
53
142
|
if (pending.size >= MAX_PENDING) {
|
|
54
|
-
throw new HostError('BUSY', `同时最多 ${MAX_PENDING}
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
const requestId = `exc-${Date.now().toString(36)}-${++seq}`;
|
|
58
|
-
/** payload 只收一层对象,超量的键直接截断,避免把整份配置塞进事件流 */
|
|
59
|
-
let args = null;
|
|
60
|
-
if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
|
|
61
|
-
args = Object.fromEntries(Object.entries(payload).slice(0, MAX_PAYLOAD_KEYS));
|
|
143
|
+
throw new HostError('BUSY', `同时最多 ${MAX_PENDING} 个外接请求,稍后再试`, 429);
|
|
62
144
|
}
|
|
63
|
-
|
|
145
|
+
const requestId = `${prefix}-${Date.now().toString(36)}-${++seq}`;
|
|
64
146
|
const promise = new Promise((resolve, reject) => {
|
|
65
147
|
/**
|
|
66
148
|
* **不要 unref**:这个定时器是请求生命周期本身的一部分。unref 之后
|
|
@@ -70,22 +152,71 @@ export function createExtBridge({ pushEvent = () => {}, timeoutMs = DEFAULT_TIME
|
|
|
70
152
|
*/
|
|
71
153
|
const timer = setTimeout(() => {
|
|
72
154
|
const p = pending.get(requestId);
|
|
73
|
-
if (p) fail(p, new HostError('TIMEOUT',
|
|
155
|
+
if (p) fail(p, new HostError('TIMEOUT', timeoutMessage(requestId), 504));
|
|
74
156
|
}, timeoutMs);
|
|
75
157
|
pending.set(requestId, { id: requestId, resolve, reject, timer, at: Date.now() });
|
|
76
158
|
});
|
|
77
159
|
|
|
78
160
|
try {
|
|
79
|
-
pushEvent(
|
|
80
|
-
requestId, extId: id, action: act, payload: args,
|
|
81
|
-
/** 调用方所在会话,DSH 侧要按它派生扩展的上下文;可为空 */
|
|
82
|
-
chat: String(chat ?? '').slice(0, 120),
|
|
83
|
-
});
|
|
161
|
+
pushEvent(event, { requestId, ...data });
|
|
84
162
|
} catch (e) {
|
|
85
163
|
const p = pending.get(requestId);
|
|
86
|
-
if (p) fail(p, new HostError('INTERNAL',
|
|
164
|
+
if (p) fail(p, new HostError('INTERNAL', `推不出事件 ${event}:${e?.message ?? e}`, 500));
|
|
165
|
+
}
|
|
166
|
+
return promise;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* 发起一次反向调用。
|
|
171
|
+
*
|
|
172
|
+
* @returns {Promise<any>} DSH 回执里的 result
|
|
173
|
+
*/
|
|
174
|
+
async function call({ extId = '', action = '', payload = null, chat = '' } = {}) {
|
|
175
|
+
const id = String(extId ?? '').trim();
|
|
176
|
+
const act = String(action ?? '').trim();
|
|
177
|
+
if (!id || !act) throw new HostError('BAD_PARAMS', '要给 extId 与 action', 400);
|
|
178
|
+
/** payload 只收一层对象,超量的键直接截断,避免把整份配置塞进事件流 */
|
|
179
|
+
let args = null;
|
|
180
|
+
if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
|
|
181
|
+
args = Object.fromEntries(Object.entries(payload).slice(0, MAX_PAYLOAD_KEYS));
|
|
87
182
|
}
|
|
88
|
-
return await
|
|
183
|
+
return await request(
|
|
184
|
+
'ext.call.request',
|
|
185
|
+
{
|
|
186
|
+
extId: id,
|
|
187
|
+
action: act,
|
|
188
|
+
payload: args,
|
|
189
|
+
/** 调用方所在会话,DSH 侧要按它派生扩展的上下文;可为空 */
|
|
190
|
+
chat: String(chat ?? '').slice(0, 120),
|
|
191
|
+
},
|
|
192
|
+
'exc',
|
|
193
|
+
() => `扩展 ${id}.${act} 没在 ${timeoutMs}ms 内回执`,
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* 触发一条外接命令。
|
|
199
|
+
*
|
|
200
|
+
* `msg` 已经由 HostBridge 序列化好(复用 `host/serialize.js`),桥只负责
|
|
201
|
+
* 转发与等回执,不认消息结构。回执形状 `{ reply }`:有正文就由调用方发。
|
|
202
|
+
*/
|
|
203
|
+
async function command({ target = 'host', extId = '', name = '', msg = null } = {}) {
|
|
204
|
+
const kind = target === 'ext' ? 'ext' : 'host';
|
|
205
|
+
const id = kind === 'ext' ? String(extId ?? '').trim() : '';
|
|
206
|
+
const nm = String(name ?? '').trim().toLowerCase();
|
|
207
|
+
if (kind === 'ext' && !id) throw new HostError('BAD_PARAMS', '扩展命令要给 extId', 400);
|
|
208
|
+
if (!CMD_NAME_RE.test(nm)) throw new HostError('BAD_PARAMS', `命令名不合法:${nm}`, 400);
|
|
209
|
+
return await request(
|
|
210
|
+
'ext.command.request',
|
|
211
|
+
{
|
|
212
|
+
target: kind,
|
|
213
|
+
extId: id,
|
|
214
|
+
name: nm,
|
|
215
|
+
msg: msg && typeof msg === 'object' ? msg : null,
|
|
216
|
+
},
|
|
217
|
+
'cmd',
|
|
218
|
+
() => `命令 /${nm} 没在 ${timeoutMs}ms 内回执`,
|
|
219
|
+
);
|
|
89
220
|
}
|
|
90
221
|
|
|
91
222
|
/** DSH 通过 RPC 回执。认不出 id 一律拒绝,别让旧回执解掉新请求 */
|
|
@@ -103,29 +234,112 @@ export function createExtBridge({ pushEvent = () => {}, timeoutMs = DEFAULT_TIME
|
|
|
103
234
|
return { ok: true, settled: key };
|
|
104
235
|
}
|
|
105
236
|
|
|
106
|
-
/**
|
|
107
|
-
|
|
237
|
+
/**
|
|
238
|
+
* 命令回执。与 `reply` 共用 pending 表,只是语义更窄:
|
|
239
|
+
* 结果是 `{ reply }`,正文超长直接截断(QQ 单条塞不下,报错没意义)。
|
|
240
|
+
*/
|
|
241
|
+
function replyCommand({ requestId = '', ok = true, reply: text = '', error = '' } = {}) {
|
|
242
|
+
const key = String(requestId ?? '').trim();
|
|
243
|
+
const p = pending.get(key);
|
|
244
|
+
if (!p) throw new HostError('NOT_FOUND', '没有这个待回执的命令(可能已超时)', 404);
|
|
245
|
+
clearTimeout(p.timer);
|
|
246
|
+
pending.delete(key);
|
|
247
|
+
if (ok === false) {
|
|
248
|
+
p.reject(new HostError('EXT_FAILED', String(error ?? '扩展命令执行失败').slice(0, 300), 502));
|
|
249
|
+
return { ok: true, settled: key, failed: true };
|
|
250
|
+
}
|
|
251
|
+
const body = String(text ?? '').slice(0, MAX_REPLY_CHARS);
|
|
252
|
+
p.resolve(body ? { reply: body } : null);
|
|
253
|
+
return { ok: true, settled: key };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** DSH 连上 / 扩展装卸后上报能力清单与命令 */
|
|
257
|
+
function register({ extensions = [], host = null } = {}) {
|
|
108
258
|
const list = Array.isArray(extensions) ? extensions : [];
|
|
109
259
|
catalog = list
|
|
110
260
|
.filter((e) => e && typeof e.id === 'string' && e.id)
|
|
111
261
|
.map((e) => ({
|
|
112
262
|
extId: e.id.slice(0, 64),
|
|
263
|
+
name: String(e.name ?? '').slice(0, 40),
|
|
113
264
|
actions: (Array.isArray(e.actions) ? e.actions : [])
|
|
114
265
|
.filter((a) => a && typeof a.id === 'string' && a.id)
|
|
115
266
|
.slice(0, 60)
|
|
116
267
|
.map((a) => ({ id: a.id.slice(0, 80), label: String(a.label ?? a.id).slice(0, 120) })),
|
|
117
268
|
}));
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* 命令清单:扩展的按扩展归属,宿主的归它自报的那个名字(`ext:<name>`)。
|
|
272
|
+
* 总数超上限就整批丢(不静默截一半),并让客户端在 `rejected` 里看到原因。
|
|
273
|
+
*/
|
|
274
|
+
const normalized = [];
|
|
275
|
+
for (const e of catalog) {
|
|
276
|
+
const src = list.find((x) => x && x.id === e.extId);
|
|
277
|
+
normalized.push(
|
|
278
|
+
...normalizeCommands(src?.commands, { target: 'ext', extId: e.extId, pluginName: e.name || e.extId }),
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
if (host && typeof host === 'object') {
|
|
282
|
+
normalized.push(...normalizeCommands(host.commands, { target: 'host', pluginName: String(host.name ?? 'dsh') }));
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
let rejected = [];
|
|
286
|
+
/** 因重名被改成 `<程序名>-<命令名>` 的条目,回执里告诉客户端,别让它悄悄改名 */
|
|
287
|
+
let renamed = [];
|
|
288
|
+
if (normalized.length > MAX_COMMANDS) {
|
|
289
|
+
rejected.push({ name: '*', reason: `命令总数 ${normalized.length} 超过上限 ${MAX_COMMANDS}` });
|
|
290
|
+
commands = [];
|
|
291
|
+
} else {
|
|
292
|
+
commands = normalized;
|
|
293
|
+
}
|
|
294
|
+
if (installCommands) {
|
|
295
|
+
try {
|
|
296
|
+
const r = installCommands(commands);
|
|
297
|
+
/**
|
|
298
|
+
* 兼容两种返回:老口径直接给 `rejected` 数组,新口径给
|
|
299
|
+
* `{rejected, renamed}`。宿主侧是同一个仓改的,但外接桥也可
|
|
300
|
+
* 单独注入(单测),留一层兼容省得两边版本错开就炸。
|
|
301
|
+
*/
|
|
302
|
+
if (Array.isArray(r)) {
|
|
303
|
+
rejected = rejected.concat(r);
|
|
304
|
+
} else {
|
|
305
|
+
rejected = rejected.concat(Array.isArray(r?.rejected) ? r.rejected : []);
|
|
306
|
+
renamed = Array.isArray(r?.renamed) ? r.renamed : [];
|
|
307
|
+
}
|
|
308
|
+
} catch (e) {
|
|
309
|
+
log(`安装外接命令失败:${e?.message ?? e}`);
|
|
310
|
+
rejected.push({ name: '*', reason: `安装失败:${e?.message ?? e}` });
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
118
314
|
catalogAt = Date.now();
|
|
119
|
-
log(
|
|
120
|
-
|
|
315
|
+
log(
|
|
316
|
+
`外接清单已更新:${catalog.length} 个扩展 / ${catalog.reduce((n, e) => n + e.actions.length, 0)} 个动作 / ` +
|
|
317
|
+
`${commands.length} 条命令${renamed.length ? `,${renamed.length} 条改名` : ''}` +
|
|
318
|
+
`${rejected.length ? `,${rejected.length} 条被拒` : ''}`,
|
|
319
|
+
);
|
|
320
|
+
return { ok: true, count: catalog.length, commands: commands.length, rejected, renamed };
|
|
121
321
|
}
|
|
122
322
|
|
|
123
323
|
return {
|
|
124
324
|
call,
|
|
325
|
+
command,
|
|
125
326
|
reply,
|
|
327
|
+
replyCommand,
|
|
126
328
|
register,
|
|
127
329
|
list: () => ({
|
|
128
|
-
extensions: catalog.map((e) => ({
|
|
330
|
+
extensions: catalog.map((e) => ({
|
|
331
|
+
extId: e.extId,
|
|
332
|
+
name: e.name,
|
|
333
|
+
actions: e.actions.map((a) => ({ ...a })),
|
|
334
|
+
commands: commands
|
|
335
|
+
.filter((c) => c.pluginId === `ext:${e.extId}`)
|
|
336
|
+
.map((c) => ({ name: c.name, aliases: [...c.aliases], desc: c.desc })),
|
|
337
|
+
})),
|
|
338
|
+
host: {
|
|
339
|
+
commands: commands
|
|
340
|
+
.filter((c) => c.target === 'host')
|
|
341
|
+
.map((c) => ({ name: c.name, aliases: [...c.aliases], desc: c.desc })),
|
|
342
|
+
},
|
|
129
343
|
updatedAt: catalogAt,
|
|
130
344
|
pending: pending.size,
|
|
131
345
|
}),
|
|
@@ -134,6 +348,15 @@ export function createExtBridge({ pushEvent = () => {}, timeoutMs = DEFAULT_TIME
|
|
|
134
348
|
for (const p of [...pending.values()]) {
|
|
135
349
|
fail(p, new HostError('DISCONNECTED', `${why},扩展调用已取消`, 503));
|
|
136
350
|
}
|
|
351
|
+
/** 命令跟着连接走:客户端没连上,这些命令点了也没人接,必须摘掉 */
|
|
352
|
+
if (commands.length && installCommands) {
|
|
353
|
+
commands = [];
|
|
354
|
+
try {
|
|
355
|
+
installCommands([]);
|
|
356
|
+
} catch (e) {
|
|
357
|
+
log(`摘除外接命令失败:${e?.message ?? e}`);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
137
360
|
},
|
|
138
361
|
pendingCount: () => pending.size,
|
|
139
362
|
};
|
|
@@ -21,9 +21,19 @@
|
|
|
21
21
|
* @param {boolean} o.silent 静默消息(@ 别的机器人 / 只回@模式的裸命令)
|
|
22
22
|
* @param {boolean} o.forwardSilent `plugins.forwardSilentToProtocol`,默认 true
|
|
23
23
|
* @param {boolean} o.duplicate 账本判定为官方重推
|
|
24
|
+
* @param {boolean} o.isCommand 命中框架命令表、会由框架自己执行的命令
|
|
24
25
|
*/
|
|
25
|
-
export function shouldForwardInbound({ hasContent, silent, forwardSilent, duplicate } = {}) {
|
|
26
|
+
export function shouldForwardInbound({ hasContent, silent, forwardSilent, duplicate, isCommand } = {}) {
|
|
26
27
|
if (!hasContent) return false;
|
|
28
|
+
/**
|
|
29
|
+
* **命令不进 AI**:`/help 插件`、`/model` 这类已经由框架(或外接客户端)执行了,
|
|
30
|
+
* 再交给协议层,模型就会把它当成用户在说话,还会写进记忆——
|
|
31
|
+
* 2026-11-28 用户反馈「发指令结果被当成聊天喂给模型」就是这么来的。
|
|
32
|
+
*
|
|
33
|
+
* 只拦**命中命令表**的:`/xyz` 这种不存在的命令仍按普通消息走,
|
|
34
|
+
* 用户真想在聊天里说以 `/` 开头的内容时不会被吞。
|
|
35
|
+
*/
|
|
36
|
+
if (isCommand) return false;
|
|
27
37
|
/** 静默消息按用户开关决定要不要给协议层(issue #38),默认照旧全交 */
|
|
28
38
|
if (silent && !forwardSilent) return false;
|
|
29
39
|
/** 官方重推:协议层只该被触发一次 */
|
package/src/host/index.js
CHANGED
|
@@ -61,28 +61,61 @@ export function serializeRpcError(e) {
|
|
|
61
61
|
};
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
-
/**
|
|
64
|
+
/**
|
|
65
|
+
* 与 OneBot 的 6700–6799 分开,方便面板上两个出口各写各的端口。
|
|
66
|
+
*
|
|
67
|
+
* 但 Windows 开了 Hyper-V / WSL 后常把 6501–7100 整段列为保留端口,
|
|
68
|
+
* 6800–6899 会整段 bind 失败,报的是 EACCES 而不是 EADDRINUSE。
|
|
69
|
+
* 所以自动端口在某段全失败时退到备用段;显式端口仍只在附近顺延,
|
|
70
|
+
* 不跨到备用段(跨段才会让对端彻底找不到)。
|
|
71
|
+
*/
|
|
65
72
|
const PORT_BASE = 6800;
|
|
66
73
|
const PORT_SPAN = 100;
|
|
67
74
|
const PORT_TRIES = 20;
|
|
75
|
+
const FALLBACK_BASE = 18300;
|
|
68
76
|
const HEARTBEAT_MS = 25_000;
|
|
69
77
|
|
|
78
|
+
/** 只有这两种 bind 错误值得换端口再试;别的错误换端口也没用 */
|
|
79
|
+
const BIND_RETRY_CODES = new Set(['EADDRINUSE', 'EACCES']);
|
|
80
|
+
|
|
81
|
+
export function shouldRetryBind(e) {
|
|
82
|
+
return BIND_RETRY_CODES.has(String(e?.code ?? ''));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** EACCES 必须说人话:让用户去「依赖」卡找不存在的依赖是最糟的提示 */
|
|
86
|
+
export function describeBindError(e, port) {
|
|
87
|
+
const code = String(e?.code ?? '');
|
|
88
|
+
if (code === 'EACCES') {
|
|
89
|
+
return `端口 ${port} 被系统保留或没有权限监听(Windows 开了 Hyper-V / WSL 时常见),请到「外接」换一个端口`;
|
|
90
|
+
}
|
|
91
|
+
if (code === 'EADDRINUSE') return `端口 ${port} 被占用,顺延后仍起不来`;
|
|
92
|
+
return `端口 ${port} 起不来:${e?.message ?? '未知原因'}`;
|
|
93
|
+
}
|
|
94
|
+
|
|
70
95
|
function portOf(botId) {
|
|
71
96
|
const h = crypto.createHash('sha1').update(String(botId)).digest();
|
|
72
97
|
return PORT_BASE + (h.readUInt16BE(0) % PORT_SPAN);
|
|
73
98
|
}
|
|
74
99
|
|
|
100
|
+
/** 自动端口先按原公式试,整段不可用时才退到备用段;显式端口只试自己那一段 */
|
|
101
|
+
function* candidatePorts(wanted, auto) {
|
|
102
|
+
for (let i = 0; i < PORT_TRIES; i++) yield wanted + i;
|
|
103
|
+
if (auto) for (let i = 0; i < PORT_TRIES; i++) yield FALLBACK_BASE + i;
|
|
104
|
+
}
|
|
105
|
+
|
|
75
106
|
export class HostBridge {
|
|
76
107
|
/**
|
|
77
108
|
* @param {object} p
|
|
78
109
|
* @param {object} p.runtime BotRuntime
|
|
79
110
|
* @param {object} p.cfg 该机器人的 `host` 配置
|
|
80
111
|
* @param {string} p.botId
|
|
112
|
+
* @param {Function} [p.createServer] 可注入的监听工厂,只为把端口失败路径钉进单测
|
|
81
113
|
*/
|
|
82
|
-
constructor({ runtime, cfg, botId }) {
|
|
114
|
+
constructor({ runtime, cfg, botId, createServer = createHostServer }) {
|
|
83
115
|
this.runtime = runtime;
|
|
84
116
|
this.cfg = cfg ?? {};
|
|
85
117
|
this.botId = botId;
|
|
118
|
+
this.createServer = createServer;
|
|
86
119
|
this.server = null;
|
|
87
120
|
this.methods = null;
|
|
88
121
|
this.state = 'stopped';
|
|
@@ -101,13 +134,23 @@ export class HostBridge {
|
|
|
101
134
|
* 才知道这个协议能干什么;createMethods 只捕获 runtime 引用,
|
|
102
135
|
* 里面的 R.api / R.plugins 都是调用时现读,早建不会拿到过期对象。
|
|
103
136
|
*/
|
|
137
|
+
/**
|
|
138
|
+
* 外接客户端注册过来的命令装在伪插件上(宿主本体 `ext:<自报名>`、扩展 `ext:<id>`)。
|
|
139
|
+
* 记下来是为了重注册 / 断线时整组摘掉——命令表是全局命名空间,
|
|
140
|
+
* 留一条僵尸命令就会一直抢别人的同名命令。
|
|
141
|
+
*/
|
|
142
|
+
this.extCommandPlugins = new Set();
|
|
104
143
|
/**
|
|
105
144
|
* 反向调用桥:框架插件调 DSH 扩展。事件走协议自己的 SSE 流,
|
|
106
145
|
* 回执走 RPC,所以不新开监听、不给 DSH 发第二套令牌。
|
|
146
|
+
*
|
|
147
|
+
* `installCommands` 让客户端上报的聊天命令真进 registry(1.2.0 起);
|
|
148
|
+
* 桥自己保持纯逻辑,不 import Registry,好单测。
|
|
107
149
|
*/
|
|
108
150
|
this.extBridge = createExtBridge({
|
|
109
151
|
pushEvent: (event, data) => this.#push(event, data),
|
|
110
152
|
log: (m) => log.info(`[ext-bridge] ${m}`),
|
|
153
|
+
installCommands: (list) => this.#installExtCommands(list),
|
|
111
154
|
});
|
|
112
155
|
this.methods = createMethods({
|
|
113
156
|
runtime: this.runtime,
|
|
@@ -128,6 +171,148 @@ export class HostBridge {
|
|
|
128
171
|
return run;
|
|
129
172
|
}
|
|
130
173
|
|
|
174
|
+
/**
|
|
175
|
+
* 把外接客户端上报的命令装进 registry。
|
|
176
|
+
*
|
|
177
|
+
* 每次调用都是「整组重建」:先按伪插件 id 清空,再按清单重装。这样扩展
|
|
178
|
+
* 卸载、改命令名、断线都不会留下僵尸命令;也天然幂等(DSH 重连会重复上报)。
|
|
179
|
+
*
|
|
180
|
+
* 重名**不直接丢**:改成 `<程序名>-<命令名>` 再试(见下面的 `namespaceOf`),
|
|
181
|
+
* 只有改了还撞才进 `rejected`。外接协议后续要接多个程序,固定前缀能保证
|
|
182
|
+
* `/dsh-model`、`/aurabot-model` 各用各的,不用抢 `/model`。
|
|
183
|
+
*
|
|
184
|
+
* @returns {{rejected: Array<{name:string, plugin?:string, reason:string}>, renamed: Array<{from:string,to:string,plugin?:string}>}}
|
|
185
|
+
*/
|
|
186
|
+
#installExtCommands(list) {
|
|
187
|
+
const registry = this.runtime?.registry;
|
|
188
|
+
const mine = Array.isArray(list) ? list : [];
|
|
189
|
+
if (!registry) return { rejected: [], renamed: [] };
|
|
190
|
+
for (const pid of this.extCommandPlugins) registry.clearPlugin(pid);
|
|
191
|
+
this.extCommandPlugins.clear();
|
|
192
|
+
|
|
193
|
+
const rejected = [];
|
|
194
|
+
const renamed = [];
|
|
195
|
+
const prefix = String(this.runtime?.cfg?.commandPrefix ?? '/');
|
|
196
|
+
|
|
197
|
+
/** 命令名上限 16(与命令表同口径);冲突改名时超长就截断,宁可短也别装不上 */
|
|
198
|
+
const fit = (s) =>
|
|
199
|
+
String(s ?? '')
|
|
200
|
+
.toLowerCase()
|
|
201
|
+
.replace(/[^\p{L}\p{N}_-]+/gu, '-')
|
|
202
|
+
.replace(/^-+|-+$/g, '')
|
|
203
|
+
.slice(0, 16);
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* 冲突时用的程序名:取外接方自报名字里的**第一段英文**(`dsh-roost` → `dsh`)。
|
|
207
|
+
* 中文名(`B 站`)提不出英文段时退回扩展 id——总得有个能拼进命令名的前缀。
|
|
208
|
+
*/
|
|
209
|
+
/**
|
|
210
|
+
* 冲突时用的程序名:优先用内部 id 去掉 `ext:`(`ext:dsh` → `dsh`,
|
|
211
|
+
* `ext:bili` → `bili`),id 不是短英文时退回自报名字的第一段英文。
|
|
212
|
+
* 中文名(`B 站`)提不出英文段时兜底 `ext`——总得有个能拼进命令名的前缀。
|
|
213
|
+
*/
|
|
214
|
+
const namespaceOf = (c) => {
|
|
215
|
+
const id = String(c.pluginId ?? '').replace(/^ext:/, '');
|
|
216
|
+
const first = (String(c.pluginName ?? '').match(/[a-z0-9]+/gi) ?? [])[0] ?? '';
|
|
217
|
+
const pick = /^[a-z0-9_-]{2,16}$/i.test(id) ? id : first;
|
|
218
|
+
return fit(pick).slice(0, 8) || 'ext';
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
for (const c of mine) {
|
|
222
|
+
const handler = (msg) => this.#runExtCommand(c, msg);
|
|
223
|
+
const ns = namespaceOf(c);
|
|
224
|
+
/**
|
|
225
|
+
* `usage` 要跟着实际注册名走:客户端写的 `/model [list|…]` 是它以为的名字,
|
|
226
|
+
* 改名成 `/dsh-model` 后菜单里还显示 `/model`,用户照着发就撞回原插件了。
|
|
227
|
+
* 做法是只保留原 usage 的**参数部分**,命令名用当前这个。
|
|
228
|
+
*/
|
|
229
|
+
const usageOf = (name) => {
|
|
230
|
+
const rest = String(c.usage ?? '').trim().replace(/^\S+\s*/, '');
|
|
231
|
+
const head = `${prefix}${name}`;
|
|
232
|
+
return (rest ? `${head} ${rest}` : head).slice(0, 120);
|
|
233
|
+
};
|
|
234
|
+
/**
|
|
235
|
+
* 因重名改过的命令要在菜单里标出来,写明它本来叫什么。
|
|
236
|
+
* 不标的话用户看到 `/dsh-model` 会以为是客户端的原始命令名,
|
|
237
|
+
* 排查「为什么我的 /model 没生效」时完全对不上。
|
|
238
|
+
*/
|
|
239
|
+
const descOf = (from) => {
|
|
240
|
+
const base = String(c.desc ?? '');
|
|
241
|
+
if (!from) return base;
|
|
242
|
+
const note = `原名 ${prefix}${from},与已有命令重名`;
|
|
243
|
+
return (base ? `${note} · ${base}` : note).slice(0, 120);
|
|
244
|
+
};
|
|
245
|
+
const metaOf = (name, extra = {}, from = '') => ({
|
|
246
|
+
desc: descOf(from),
|
|
247
|
+
usage: usageOf(name),
|
|
248
|
+
pattern: name,
|
|
249
|
+
admin: c.admin,
|
|
250
|
+
globalAdmin: c.globalAdmin,
|
|
251
|
+
ownerOnly: c.ownerOnly,
|
|
252
|
+
/** 客户端可以要求「能直呼但不进菜单」,与插件命令的 hidden 同义 */
|
|
253
|
+
hidden: c.hidden,
|
|
254
|
+
plugin: c.pluginName,
|
|
255
|
+
pluginId: c.pluginId,
|
|
256
|
+
/** 宿主命令进「指令」组,扩展命令单独一组,免得把内核菜单挤乱 */
|
|
257
|
+
section: c.target === 'host' ? '指令' : '扩展',
|
|
258
|
+
...extra,
|
|
259
|
+
});
|
|
260
|
+
/** 别名单独注册成隐藏命令:菜单里只显示主名,名字仍可直呼 */
|
|
261
|
+
for (const [i, name] of [c.name, ...c.aliases].entries()) {
|
|
262
|
+
const isPrimary = i === 0;
|
|
263
|
+
try {
|
|
264
|
+
registry.addCommand(c.pluginId, name, metaOf(name, isPrimary ? {} : { hidden: true }), handler);
|
|
265
|
+
continue;
|
|
266
|
+
} catch (e) {
|
|
267
|
+
const alt = fit(`${ns}-${name}`);
|
|
268
|
+
if (alt && alt !== name) {
|
|
269
|
+
try {
|
|
270
|
+
/** 改名注册时把原名带进 desc,菜单里能看出「这条本来叫 /model」 */
|
|
271
|
+
registry.addCommand(c.pluginId, alt, metaOf(alt, isPrimary ? {} : { hidden: true }, name), handler);
|
|
272
|
+
renamed.push({ from: name, to: alt, plugin: c.pluginName });
|
|
273
|
+
log.info(`外接命令 /${name} 与已有命令冲突,改注册为 /${alt}`);
|
|
274
|
+
continue;
|
|
275
|
+
} catch (e2) {
|
|
276
|
+
rejected.push({ name, plugin: c.pluginName, reason: String(e2?.message ?? e2).slice(0, 120) });
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
rejected.push({ name, plugin: c.pluginName, reason: String(e?.message ?? e).slice(0, 120) });
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
this.extCommandPlugins.add(c.pluginId);
|
|
284
|
+
}
|
|
285
|
+
if (renamed.length) {
|
|
286
|
+
log.info(`外接命令有 ${renamed.length} 条因重名改了名:${renamed.map((r) => `/${r.from}→/${r.to}`).join(';')}`);
|
|
287
|
+
}
|
|
288
|
+
if (rejected.length) {
|
|
289
|
+
log.warn(
|
|
290
|
+
`外接命令有 ${rejected.length} 条没装上:${rejected.map((r) => `${r.name}(${r.reason})`).join(';')}`,
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
return { rejected, renamed };
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* 命令命中:转发给外接客户端,等它回执。
|
|
298
|
+
*
|
|
299
|
+
* 回执带 `reply` 就由框架发(`msg.reply` 自带引用与限频),不带说明客户端
|
|
300
|
+
* 自己发过了。失败一律回一句人话——群里「发了命令没反应」比报错更难查。
|
|
301
|
+
*/
|
|
302
|
+
async #runExtCommand(c, msg) {
|
|
303
|
+
const payload = serializeMessage(msg, {
|
|
304
|
+
groupName: this.runtime?.groupNames?.get?.(msg.groupId)?.name ?? '',
|
|
305
|
+
});
|
|
306
|
+
try {
|
|
307
|
+
const r = await this.extBridge.command({ target: c.target, extId: c.extId, name: c.name, msg: payload });
|
|
308
|
+
const text = String(r?.reply ?? '').trim();
|
|
309
|
+
if (text) await msg.reply(text);
|
|
310
|
+
} catch (e) {
|
|
311
|
+
log.warn(`外接命令 /${c.name} 失败:${e?.message ?? e}`);
|
|
312
|
+
await msg.reply(`「${c.pluginName}」没接住这个命令:${e?.message ?? e}`).catch(() => {});
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
131
316
|
start() {
|
|
132
317
|
return this.#enqueue(() => this.#startNow());
|
|
133
318
|
}
|
|
@@ -199,7 +384,7 @@ export class HostBridge {
|
|
|
199
384
|
|
|
200
385
|
await this.#version();
|
|
201
386
|
/** 端口写在构造参数里,被占只能重建实例;每次只建一个,别让失败的实例堆着计时器 */
|
|
202
|
-
const make = (p) =>
|
|
387
|
+
const make = (p) => this.createServer({
|
|
203
388
|
host: listenHost,
|
|
204
389
|
port: p,
|
|
205
390
|
token: String(this.cfg.token ?? ''),
|
|
@@ -215,9 +400,11 @@ export class HostBridge {
|
|
|
215
400
|
});
|
|
216
401
|
|
|
217
402
|
const wanted = Number(this.cfg.port) || portOf(this.botId);
|
|
403
|
+
const auto = !Number(this.cfg.port);
|
|
218
404
|
let lastErr = null;
|
|
219
|
-
|
|
220
|
-
|
|
405
|
+
let lastPort = wanted;
|
|
406
|
+
for (const p of candidatePorts(wanted, auto)) {
|
|
407
|
+
lastPort = p;
|
|
221
408
|
const attempt = make(p);
|
|
222
409
|
try {
|
|
223
410
|
this.port = await attempt.start();
|
|
@@ -226,13 +413,13 @@ export class HostBridge {
|
|
|
226
413
|
} catch (e) {
|
|
227
414
|
lastErr = e;
|
|
228
415
|
await attempt.stop().catch(() => {});
|
|
229
|
-
if (e
|
|
416
|
+
if (!shouldRetryBind(e)) break;
|
|
230
417
|
}
|
|
231
418
|
}
|
|
232
419
|
|
|
233
420
|
if (!this.server) {
|
|
234
421
|
this.state = 'error';
|
|
235
|
-
this.error =
|
|
422
|
+
this.error = describeBindError(lastErr, lastPort);
|
|
236
423
|
log.error(this.error);
|
|
237
424
|
return this;
|
|
238
425
|
}
|
package/src/host/methods.js
CHANGED
|
@@ -1157,9 +1157,18 @@ export function createMethods({ runtime: R, getState, log = () => {}, extBridge
|
|
|
1157
1157
|
def('ext.call.reply', 'message', 'DSH 回传扩展调用结果(内部)', async (p) =>
|
|
1158
1158
|
extBridge.reply({ requestId: str(p.requestId), ok: p.ok !== false, result: p.result ?? null, error: str(p.error ?? '') }));
|
|
1159
1159
|
|
|
1160
|
-
/**
|
|
1161
|
-
|
|
1162
|
-
|
|
1160
|
+
/**
|
|
1161
|
+
* 命令回执:客户端处理完 `ext.command.request` 后回这一条。
|
|
1162
|
+
* 带 `reply` 就由框架代发(带引用、受限频与被动窗口管),不带就是客户端自己发过了。
|
|
1163
|
+
*/
|
|
1164
|
+
def('ext.command.reply', 'message', 'DSH 回传命令执行结果,可选代发正文(内部)', async (p) =>
|
|
1165
|
+
extBridge.replyCommand({
|
|
1166
|
+
requestId: str(p.requestId), ok: p.ok !== false, reply: str(p.reply ?? ''), error: str(p.error ?? ''),
|
|
1167
|
+
}));
|
|
1168
|
+
|
|
1169
|
+
/** DSH 连上 / 扩展装卸后上报能力清单与命令(`host` 为宿主本体,1.2.0 起) */
|
|
1170
|
+
def('ext.register', 'message', 'DSH 上报已装扩展能力清单与聊天命令(内部)', async (p) =>
|
|
1171
|
+
extBridge.register({ extensions: p.extensions ?? [], host: p.host ?? null }));
|
|
1163
1172
|
}
|
|
1164
1173
|
|
|
1165
1174
|
/* ---------------- 插件工具 → 一等协议方法(方案 A) ---------------- */
|