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
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 宿主协议的统一发送出口
|
|
3
|
+
* ====================
|
|
4
|
+
*
|
|
5
|
+
* **协议侧发消息必须走 `R.outbound`,不能直连 `R.api`。**
|
|
6
|
+
*
|
|
7
|
+
* ai-chat 在 `index.js` 的 `/r/send` 上专门写过这条警告,原因一样:
|
|
8
|
+
* `R.api.sendGroup()` 只是「打一次官方接口」,而 `R.outbound.send()` 才是框架的
|
|
9
|
+
* 出站调度器,它额外负责:
|
|
10
|
+
*
|
|
11
|
+
* · 离线判断(没连上就别打接口)
|
|
12
|
+
* · 每秒限速 / 每分钟主动消息条数上限
|
|
13
|
+
* · 主动消息日额度(默认 1000 条/天)
|
|
14
|
+
* · 被动回复窗口检查(群 5 分钟 / 单聊 60 分钟),快过期就降级为主动消息
|
|
15
|
+
* · 被动回复次数上限(群 5 次 / 单聊 4 次,撞 40034128 之前本地拦)
|
|
16
|
+
* · 审核识别(304023 → `pending`,不是失败)
|
|
17
|
+
* · 投递账本(`delivery.get` 的前置:不走 outbound 就永远查不到终态)
|
|
18
|
+
* · `dry` 演练模式
|
|
19
|
+
*
|
|
20
|
+
* 之前的实现四条发送路径(msg.send / media.send / media.image.send / msg.stream)
|
|
21
|
+
* 全是 `api.sendGroup(...)` 直发,上面这些一条都不参与——主动搭话等于裸奔,
|
|
22
|
+
* 审核之后也没人知道结果。这里统一收口。
|
|
23
|
+
*
|
|
24
|
+
* ## 为什么保留直连兜底
|
|
25
|
+
*
|
|
26
|
+
* `R.outbound` 在机器人连上之前是 `null`(bot.js 先赋 null,等连接建立才 new)。
|
|
27
|
+
* 启动早期收到发送请求时只能直发,但**必须打日志**——静默绕过会让额度账本
|
|
28
|
+
* 变成半真,比不支持更糟。
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/** 账本里这条消息的归属。固定值,不接受协议参数覆盖(避免伪造发送方) */
|
|
32
|
+
export const HOST_PLUGIN = 'host';
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 被动回复窗口判断只看 `receivedAt`(outbound.js 里 `age = receivedAt ? ... : 0`)。
|
|
36
|
+
*
|
|
37
|
+
* 不传就等于「刚收到」,窗口检查永远不触发,过期消息会被当成新鲜消息发出去,
|
|
38
|
+
* 最后由官方返回 40034xxx 报错收拾。所以客户端没给时,按 eventId 去事件账本
|
|
39
|
+
* 反查一次收到时间——`events` 表的主键就是 eventId,`get()` 拿得到 `at`。
|
|
40
|
+
*
|
|
41
|
+
* @param {object} R BotRuntime
|
|
42
|
+
* @param {object} p 协议参数
|
|
43
|
+
* @returns {number} 毫秒时间戳;拿不到返回 0(交给 outbound 按「不判断」处理)
|
|
44
|
+
*/
|
|
45
|
+
export function receivedAtOf(R, p) {
|
|
46
|
+
const direct = Number(p?.receivedAt) || 0;
|
|
47
|
+
if (direct > 0) return direct;
|
|
48
|
+
const eid = String(p?.eventId ?? '').trim();
|
|
49
|
+
if (!eid) return 0;
|
|
50
|
+
try {
|
|
51
|
+
const row = R?.ledger?.get?.(eid);
|
|
52
|
+
if (row?.at) return Number(row.at);
|
|
53
|
+
} catch {
|
|
54
|
+
/* 账本没开 / 查不到:当成不知道,别因为反查失败拦住发送 */
|
|
55
|
+
}
|
|
56
|
+
return 0;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 发一条消息(文本或富媒体),统一走 outbound。
|
|
61
|
+
*
|
|
62
|
+
* @param {object} p
|
|
63
|
+
* @param {object} p.R BotRuntime
|
|
64
|
+
* @param {(m:string)=>void} [p.log]
|
|
65
|
+
* @param {'group'|'c2c'} p.kind
|
|
66
|
+
* @param {string} p.chatId
|
|
67
|
+
* @param {object} p.payload 交给 api.js 的报文(驼峰字段:msgId / msgSeq / media …)
|
|
68
|
+
* @param {number} [p.receivedAt] 这条消息的接收时间,用于被动窗口判断
|
|
69
|
+
* @param {string} [p.requestId] 投递账本幂等键(跨重启有效,比 clientMsgId 强)
|
|
70
|
+
* @param {number} [p.fileType] 1 图 / 2 视频 / 3 语音 / 4 文件,只用于账本占位
|
|
71
|
+
* @returns {Promise<{id:string, pending:boolean, requestId:string, reused:boolean, raw:any}>}
|
|
72
|
+
*/
|
|
73
|
+
export async function sendOut({
|
|
74
|
+
R,
|
|
75
|
+
log = () => {},
|
|
76
|
+
kind,
|
|
77
|
+
chatId,
|
|
78
|
+
payload,
|
|
79
|
+
receivedAt = 0,
|
|
80
|
+
requestId = '',
|
|
81
|
+
fileType = null,
|
|
82
|
+
}) {
|
|
83
|
+
const k = kind === 'group' ? 'group' : 'c2c';
|
|
84
|
+
const target = String(chatId ?? '');
|
|
85
|
+
const body = payload && typeof payload === 'object' ? payload : {};
|
|
86
|
+
const rid = String(requestId ?? '').trim();
|
|
87
|
+
|
|
88
|
+
const ob = R?.outbound;
|
|
89
|
+
if (ob && typeof ob.send === 'function') {
|
|
90
|
+
const r = await ob.send({
|
|
91
|
+
kind: k,
|
|
92
|
+
target,
|
|
93
|
+
/** 限速 / 额度都是按 `kind:chatId` 记账的,和框架其他地方保持同一口径 */
|
|
94
|
+
chatKey: `${k}:${target}`,
|
|
95
|
+
payload: body,
|
|
96
|
+
...(receivedAt ? { receivedAt: Number(receivedAt) } : {}),
|
|
97
|
+
...(rid ? { requestId: rid } : {}),
|
|
98
|
+
...(fileType != null ? { fileType: Number(fileType) } : {}),
|
|
99
|
+
plugin: HOST_PLUGIN,
|
|
100
|
+
});
|
|
101
|
+
return {
|
|
102
|
+
id: String(r?.id ?? ''),
|
|
103
|
+
pending: Boolean(r?.pending),
|
|
104
|
+
requestId: String(r?.requestId ?? rid ?? ''),
|
|
105
|
+
reused: Boolean(r?.reused),
|
|
106
|
+
raw: r?.raw ?? r ?? null,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* 兜底直发。只在机器人启动早期(outbound 还没 new 出来)走到,
|
|
112
|
+
* 打日志是因为这条路径**不参与限速和额度**,事后排查要看得到。
|
|
113
|
+
*/
|
|
114
|
+
log(`外接协议:outbound 未就绪,这条消息直连官方接口(不限速、不记额度、不进投递账本)`);
|
|
115
|
+
const api = R?.api;
|
|
116
|
+
if (!api) throw new Error('官方接口未就绪');
|
|
117
|
+
const r = k === 'group' ? await api.sendGroup(target, body) : await api.sendC2C(target, body);
|
|
118
|
+
return {
|
|
119
|
+
id: String(r?.id ?? r?.msgId ?? ''),
|
|
120
|
+
pending: Number(r?.code) === 304023,
|
|
121
|
+
requestId: rid,
|
|
122
|
+
reused: false,
|
|
123
|
+
raw: r ?? null,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 宿主协议 v1:框架侧桥接
|
|
3
|
+
* ========================
|
|
4
|
+
*
|
|
5
|
+
* 挂在每只鸟上(`runtime.host`),一只鸟一个端口。
|
|
6
|
+
* 生命周期与 `OneBotBridge` 同构:只构造不启动,等 api / plugins / identity
|
|
7
|
+
* 都就绪再 `start()`;任何失败都只是「这一层不可用」,**不影响机器人本体**。
|
|
8
|
+
*
|
|
9
|
+
* 与内核的接口:
|
|
10
|
+
* onMessage(msg) 每条入站消息(原生结构,不翻译)
|
|
11
|
+
* onEvent(name, d) 非消息事件
|
|
12
|
+
* snapshot()/capability() 面板用
|
|
13
|
+
*
|
|
14
|
+
* **`ws` 是可选依赖**:协议有两条等价通道——`GET /ws`(双向帧)和
|
|
15
|
+
* `GET /events`(SSE,只推)+ `POST /rpc`。只读 SSE 的客户端(例如
|
|
16
|
+
* dsh-roost,它坚持零依赖、用 Node 自带 fetch 读 SSE)**完全不需要 ws**。
|
|
17
|
+
* 所以缺 ws 时照样监听,只是不开 `/ws`;`snapshot().transports` 会如实说明。
|
|
18
|
+
* 用户从 tar 包升级、没跑过 npm install 也不会因此起不来。
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import crypto from 'node:crypto';
|
|
22
|
+
import fs from 'node:fs/promises';
|
|
23
|
+
import path from 'node:path';
|
|
24
|
+
import { ROOT } from '../paths.js';
|
|
25
|
+
import { createLogger } from '../logger.js';
|
|
26
|
+
import * as deps from '../ext-deps.js';
|
|
27
|
+
import { createHostServer } from './server.js';
|
|
28
|
+
import { createMethods, effectiveScopes, HostError, HOST_PROTOCOL } from './methods.js';
|
|
29
|
+
import { serializeMessage, serializeNotice } from './serialize.js';
|
|
30
|
+
|
|
31
|
+
const log = createLogger('host');
|
|
32
|
+
|
|
33
|
+
/** 与 OneBot 的 6700–6799 分开,方便面板上两个出口各写各的端口 */
|
|
34
|
+
const PORT_BASE = 6800;
|
|
35
|
+
const PORT_SPAN = 100;
|
|
36
|
+
const PORT_TRIES = 20;
|
|
37
|
+
const HEARTBEAT_MS = 25_000;
|
|
38
|
+
|
|
39
|
+
function portOf(botId) {
|
|
40
|
+
const h = crypto.createHash('sha1').update(String(botId)).digest();
|
|
41
|
+
return PORT_BASE + (h.readUInt16BE(0) % PORT_SPAN);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export class HostBridge {
|
|
45
|
+
/**
|
|
46
|
+
* @param {object} p
|
|
47
|
+
* @param {object} p.runtime BotRuntime
|
|
48
|
+
* @param {object} p.cfg 该机器人的 `host` 配置
|
|
49
|
+
* @param {string} p.botId
|
|
50
|
+
*/
|
|
51
|
+
constructor({ runtime, cfg, botId }) {
|
|
52
|
+
this.runtime = runtime;
|
|
53
|
+
this.cfg = cfg ?? {};
|
|
54
|
+
this.botId = botId;
|
|
55
|
+
this.server = null;
|
|
56
|
+
this.methods = null;
|
|
57
|
+
this.state = 'stopped';
|
|
58
|
+
this.error = '';
|
|
59
|
+
this.port = 0;
|
|
60
|
+
this.version = '';
|
|
61
|
+
this.seq = 0;
|
|
62
|
+
this.buffer = [];
|
|
63
|
+
this.lastEventAt = 0;
|
|
64
|
+
this.startedAt = 0;
|
|
65
|
+
this.counters = { ok: 0, fail: 0 };
|
|
66
|
+
this.scopes = effectiveScopes(this.cfg);
|
|
67
|
+
/**
|
|
68
|
+
* 方法表构造时就建好,不放在 #startNow 里。
|
|
69
|
+
* 面板在协议「未开启」时也要能看到完整能力清单,否则用户得先开监听
|
|
70
|
+
* 才知道这个协议能干什么;createMethods 只捕获 runtime 引用,
|
|
71
|
+
* 里面的 R.api / R.plugins 都是调用时现读,早建不会拿到过期对象。
|
|
72
|
+
*/
|
|
73
|
+
this.methods = createMethods({
|
|
74
|
+
runtime: this.runtime,
|
|
75
|
+
getState: () => this.#state(),
|
|
76
|
+
log: (m) => log.info(m),
|
|
77
|
+
});
|
|
78
|
+
/** 插件工具集签名:变了就往事件流推一条 capabilities.changed */
|
|
79
|
+
this.toolSig = this.methods?.toolSignature?.() ?? '';
|
|
80
|
+
this.heartbeat = null;
|
|
81
|
+
/** start/stop/reconfigure 串行化:面板连点保存不能起两个监听 */
|
|
82
|
+
this.chain = Promise.resolve();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
#enqueue(fn) {
|
|
86
|
+
const run = this.chain.then(fn, fn);
|
|
87
|
+
this.chain = run.then(() => undefined, () => undefined);
|
|
88
|
+
return run;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
start() {
|
|
92
|
+
return this.#enqueue(() => this.#startNow());
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
stop() {
|
|
96
|
+
return this.#enqueue(() => this.#stopNow());
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 配置热更新:先停再起(端口 / 开关 / scope 都可能变) */
|
|
100
|
+
reconfigure(next) {
|
|
101
|
+
this.cfg = next ?? {};
|
|
102
|
+
this.scopes = effectiveScopes(this.cfg);
|
|
103
|
+
return this.#enqueue(() => this.#startNow());
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async #version() {
|
|
107
|
+
if (this.version) return this.version;
|
|
108
|
+
try {
|
|
109
|
+
const p = JSON.parse(await fs.readFile(path.join(ROOT, 'package.json'), 'utf8'));
|
|
110
|
+
this.version = String(p.version ?? '');
|
|
111
|
+
} catch {
|
|
112
|
+
this.version = '';
|
|
113
|
+
}
|
|
114
|
+
return this.version;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async #startNow() {
|
|
118
|
+
await this.#stopNow();
|
|
119
|
+
this.error = '';
|
|
120
|
+
/** 每轮重置:上一轮有 ws 不代表这一轮还加载得到 */
|
|
121
|
+
this.wsMissing = true;
|
|
122
|
+
this.scopes = effectiveScopes(this.cfg);
|
|
123
|
+
|
|
124
|
+
if (!this.cfg.enabled) {
|
|
125
|
+
this.state = 'disabled';
|
|
126
|
+
return this;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* `ws` 是**可选**依赖(和 OneBot 兼容层共用同一份按需安装)。
|
|
131
|
+
* 缺了不影响 HTTP / SSE 通道,只是没有 `/ws`——所以这里不拦启动。
|
|
132
|
+
*/
|
|
133
|
+
/** 空 token 拒绝监听:不监听比「不校验」安全得多 */
|
|
134
|
+
if (!String(this.cfg.token ?? '').trim()) {
|
|
135
|
+
this.state = 'error';
|
|
136
|
+
this.error = '没设 access token(面板「外接」页点『生成』)';
|
|
137
|
+
return this;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const listenHost = String(this.cfg.host || '127.0.0.1');
|
|
141
|
+
const loop = ['127.0.0.1', 'localhost', '::1'].includes(listenHost.toLowerCase());
|
|
142
|
+
if (!loop && !this.cfg.allowRemote) {
|
|
143
|
+
this.state = 'error';
|
|
144
|
+
this.error = `监听 ${listenHost} 会把能管理框架的接口摆到局域网上,请显式打开 allowRemote`;
|
|
145
|
+
return this;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
let wsMod = null;
|
|
149
|
+
try {
|
|
150
|
+
const m = await deps.load('ws');
|
|
151
|
+
if (m?.WebSocketServer) wsMod = m;
|
|
152
|
+
} catch (e) {
|
|
153
|
+
log.warn(`ws 加载失败,只开 HTTP + SSE:${e.message}`);
|
|
154
|
+
}
|
|
155
|
+
/** 没 ws 也要记住原因,面板据此显示「只有 SSE」而不是「坏了」 */
|
|
156
|
+
this.wsMissing = !wsMod;
|
|
157
|
+
|
|
158
|
+
await this.#version();
|
|
159
|
+
/** 端口写在构造参数里,被占只能重建实例;每次只建一个,别让失败的实例堆着计时器 */
|
|
160
|
+
const make = (p) => createHostServer({
|
|
161
|
+
host: listenHost,
|
|
162
|
+
port: p,
|
|
163
|
+
token: String(this.cfg.token ?? ''),
|
|
164
|
+
ws: wsMod,
|
|
165
|
+
maxConnections: Number(this.cfg.maxConnections) || 4,
|
|
166
|
+
attach: (_sink, info) => this.#attach(info),
|
|
167
|
+
onRpc: (frame, ctx) => this.#rpc(frame, ctx),
|
|
168
|
+
health: () => ({
|
|
169
|
+
state: this.state,
|
|
170
|
+
connections: this.server?.connections ?? 0,
|
|
171
|
+
seq: this.seq,
|
|
172
|
+
}),
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
const wanted = Number(this.cfg.port) || portOf(this.botId);
|
|
176
|
+
let lastErr = null;
|
|
177
|
+
for (let i = 0; i < PORT_TRIES; i++) {
|
|
178
|
+
const p = wanted + i;
|
|
179
|
+
const attempt = make(p);
|
|
180
|
+
try {
|
|
181
|
+
this.port = await attempt.start();
|
|
182
|
+
this.server = attempt;
|
|
183
|
+
break;
|
|
184
|
+
} catch (e) {
|
|
185
|
+
lastErr = e;
|
|
186
|
+
await attempt.stop().catch(() => {});
|
|
187
|
+
if (e?.code !== 'EADDRINUSE') break;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (!this.server) {
|
|
192
|
+
this.state = 'error';
|
|
193
|
+
this.error = `端口 ${wanted} 起不来:${lastErr?.message ?? '未知原因'}`;
|
|
194
|
+
log.error(this.error);
|
|
195
|
+
return this;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
this.state = 'running';
|
|
199
|
+
this.startedAt = Date.now();
|
|
200
|
+
this.heartbeat = setInterval(() => {
|
|
201
|
+
/** 不进缓冲、不增 seq:它只是保活,重连补拉不该把它算成事件 */
|
|
202
|
+
this.server?.broadcast({ type: 'heartbeat', at: Date.now(), seq: this.seq });
|
|
203
|
+
}, HEARTBEAT_MS);
|
|
204
|
+
this.heartbeat.unref?.();
|
|
205
|
+
|
|
206
|
+
log.info(
|
|
207
|
+
`宿主协议已监听 ${listenHost}:${this.port}` +
|
|
208
|
+
`(roost-host/1,scope: ${[...this.scopes].join('+')})`,
|
|
209
|
+
);
|
|
210
|
+
return this;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async #stopNow() {
|
|
214
|
+
if (this.heartbeat) {
|
|
215
|
+
clearInterval(this.heartbeat);
|
|
216
|
+
this.heartbeat = null;
|
|
217
|
+
}
|
|
218
|
+
if (this.server) {
|
|
219
|
+
await this.server.stop().catch((e) => log.warn(`关监听失败:${e.message}`));
|
|
220
|
+
this.server = null;
|
|
221
|
+
}
|
|
222
|
+
if (this.state === 'running') this.state = 'stopped';
|
|
223
|
+
this.port = 0;
|
|
224
|
+
return this;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/* ---------------- 帧 ---------------- */
|
|
228
|
+
|
|
229
|
+
#state() {
|
|
230
|
+
return {
|
|
231
|
+
seq: this.seq,
|
|
232
|
+
connections: this.server?.connections ?? 0,
|
|
233
|
+
startedAt: this.startedAt,
|
|
234
|
+
version: this.version,
|
|
235
|
+
counters: { ...this.counters },
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* 同步生成 welcome + 补拉。必须是同步的:JS 单线程下这一步中间不会插入
|
|
241
|
+
* broadcast,补拉和实时推送才不会重复或漏。
|
|
242
|
+
*/
|
|
243
|
+
#attach(info) {
|
|
244
|
+
const since = Number(info?.since) || 0;
|
|
245
|
+
return {
|
|
246
|
+
welcome: {
|
|
247
|
+
protocol: HOST_PROTOCOL,
|
|
248
|
+
app: 'roost-host',
|
|
249
|
+
version: this.version,
|
|
250
|
+
bot: {
|
|
251
|
+
id: this.runtime.id,
|
|
252
|
+
name: this.runtime.name,
|
|
253
|
+
appId: String(this.runtime.cfg?.appId ?? ''),
|
|
254
|
+
state: this.runtime.state,
|
|
255
|
+
online: Boolean(this.runtime.online),
|
|
256
|
+
},
|
|
257
|
+
seq: this.seq,
|
|
258
|
+
scopes: [...this.scopes],
|
|
259
|
+
dynamicTools: true,
|
|
260
|
+
features: this.methods?.names() ?? [],
|
|
261
|
+
},
|
|
262
|
+
frames: this.replaySince(since),
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* 差太多就明说,不让丢消息变成静默。
|
|
268
|
+
* 不做成 #private:补拉边界(缓冲过期 / 恰好接上)是必须能被测试钉死的契约,
|
|
269
|
+
* 私有方法只能靠「起一个真服务」间接验,太脆。
|
|
270
|
+
*/
|
|
271
|
+
replaySince(since) {
|
|
272
|
+
if (!Number.isFinite(since) || since <= 0) return [];
|
|
273
|
+
const oldest = this.buffer.length ? this.buffer[0].seq : this.seq + 1;
|
|
274
|
+
if (since < oldest - 1) {
|
|
275
|
+
return [{
|
|
276
|
+
type: 'gap', since, seq: this.seq, oldest,
|
|
277
|
+
message: '缓冲里已经没有那么早的事件了,请自行重开会话',
|
|
278
|
+
}];
|
|
279
|
+
}
|
|
280
|
+
return this.buffer
|
|
281
|
+
.filter((e) => e.seq > since)
|
|
282
|
+
.map((e) => ({ type: 'event', ...e }));
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** 统一的 RPC 分发:HTTP /rpc 与 WS req 走同一条路 */
|
|
286
|
+
async #rpc(frame, ctx) {
|
|
287
|
+
const id = frame?.id ?? '';
|
|
288
|
+
try {
|
|
289
|
+
if (this.state !== 'running' || !this.methods) {
|
|
290
|
+
throw new HostError('NOT_READY', '宿主协议还没就绪', 503);
|
|
291
|
+
}
|
|
292
|
+
const data = await this.methods.call(frame.method, frame.params ?? {}, {
|
|
293
|
+
scopes: this.scopes,
|
|
294
|
+
client: ctx?.via ?? '',
|
|
295
|
+
});
|
|
296
|
+
this.counters.ok += 1;
|
|
297
|
+
/**
|
|
298
|
+
* 插件启停 / 热重载会让工具集变化。客户端不该把 `features` 当静态清单:
|
|
299
|
+
* 变了就推一条事件,让它重新拉 `system.capabilities`。
|
|
300
|
+
*/
|
|
301
|
+
const sig = this.methods.toolSignature?.() ?? '';
|
|
302
|
+
if (sig !== this.toolSig) {
|
|
303
|
+
this.toolSig = sig;
|
|
304
|
+
this.#push('capabilities.changed', {
|
|
305
|
+
features: this.methods.names(),
|
|
306
|
+
tools: this.methods.describe().filter((m) => m.name.startsWith('tool.')),
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
return { id, ok: true, data: data ?? null, http: 200 };
|
|
310
|
+
} catch (e) {
|
|
311
|
+
this.counters.fail += 1;
|
|
312
|
+
const code = e instanceof HostError ? e.code : 'INTERNAL';
|
|
313
|
+
const http = Number(e?.http) || (code === 'NO_SCOPE' ? 403 : code === 'NOT_FOUND' ? 404
|
|
314
|
+
: code === 'NOT_READY' ? 503 : code === 'INTERNAL' ? 500 : 400);
|
|
315
|
+
return {
|
|
316
|
+
id, ok: false, http,
|
|
317
|
+
error: { code, message: String(e?.message ?? e) },
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
#push(event, data) {
|
|
323
|
+
const seq = ++this.seq;
|
|
324
|
+
const item = { seq, event, data, at: Date.now() };
|
|
325
|
+
const ttl = Number(this.cfg.historyTtlMs) || 3_600_000;
|
|
326
|
+
const limit = Math.min(Math.max(Number(this.cfg.historyLimit) || 200, 0), 1000);
|
|
327
|
+
const cut = Date.now() - ttl;
|
|
328
|
+
while (this.buffer.length && (this.buffer[0].at < cut || this.buffer.length >= limit)) {
|
|
329
|
+
this.buffer.shift();
|
|
330
|
+
}
|
|
331
|
+
this.buffer.push(item);
|
|
332
|
+
this.server?.broadcast({ type: 'event', ...item });
|
|
333
|
+
this.lastEventAt = item.at;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/* ---------------- 内核回调 ---------------- */
|
|
337
|
+
|
|
338
|
+
onMessage(msg) {
|
|
339
|
+
if (this.state !== 'running' || !msg?.chatId) return;
|
|
340
|
+
/** 全量模式下平台会回推自己发的消息,不滤掉会自激循环 */
|
|
341
|
+
if (msg.raw?.author?.bot === true) return;
|
|
342
|
+
if (this.cfg.forwardAll === false && !msg.addressed) return;
|
|
343
|
+
const groupName = msg.kind === 'group'
|
|
344
|
+
? (this.runtime.groupNames?.get?.(msg.groupId)?.name ?? '')
|
|
345
|
+
: '';
|
|
346
|
+
const data = serializeMessage(msg, { groupName });
|
|
347
|
+
if (!data) return;
|
|
348
|
+
try {
|
|
349
|
+
this.#push('message', data);
|
|
350
|
+
} catch (e) {
|
|
351
|
+
log.warn(`事件序列化失败(已跳过):${e.message}`);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
onEvent(eventName, d) {
|
|
356
|
+
if (this.state !== 'running') return;
|
|
357
|
+
try {
|
|
358
|
+
this.#push('notice', serializeNotice(eventName, d));
|
|
359
|
+
} catch (e) {
|
|
360
|
+
log.warn(`通知序列化失败(${eventName}):${e.message}`);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/* ---------------- 面板 ---------------- */
|
|
365
|
+
|
|
366
|
+
capability() {
|
|
367
|
+
return {
|
|
368
|
+
protocol: HOST_PROTOCOL,
|
|
369
|
+
scopes: [...this.scopes],
|
|
370
|
+
methods: this.methods?.describe() ?? [],
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
snapshot() {
|
|
375
|
+
return {
|
|
376
|
+
state: this.state,
|
|
377
|
+
error: this.error,
|
|
378
|
+
/**
|
|
379
|
+
* 实际开出来的通道。`ws:false` 只表示没有双向帧,
|
|
380
|
+
* `/rpc` + `/events` 仍在——客户端不该据此判定「协议不可用」。
|
|
381
|
+
*/
|
|
382
|
+
transports: { http: true, sse: true, ws: Boolean(this.wsMissing === false) },
|
|
383
|
+
host: this.cfg.host || '127.0.0.1',
|
|
384
|
+
port: this.port || 0,
|
|
385
|
+
connections: this.server?.connections ?? 0,
|
|
386
|
+
seq: this.seq,
|
|
387
|
+
buffered: this.buffer.length,
|
|
388
|
+
lastEventAt: this.lastEventAt,
|
|
389
|
+
actions: { ...this.counters },
|
|
390
|
+
scopes: [...this.scopes],
|
|
391
|
+
online: Boolean(this.runtime.online),
|
|
392
|
+
mode: 'parallel',
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
}
|