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.
Files changed (55) hide show
  1. package/README.md +10 -3
  2. package/config/bot.example.json +30 -0
  3. package/docs/AI/345/256/277/344/270/273/346/216/245/345/205/245.md +145 -0
  4. package/docs/DSH/346/216/245/345/205/245.md +267 -0
  5. package/docs/OneBot/345/205/274/345/256/271/345/261/202/350/256/276/350/256/241.md +1032 -0
  6. package/docs/images/bot-menu.png +0 -0
  7. package/docs/images/bot-switcher.png +0 -0
  8. package/docs/images/events.png +0 -0
  9. package/docs/images/group-manage.png +0 -0
  10. package/docs/images/logs.png +0 -0
  11. package/docs/images/overview.png +0 -0
  12. package/docs/images/plugin-dash-tab.png +0 -0
  13. package/docs/images/plugins-dash.png +0 -0
  14. package/docs/images/plugins.png +0 -0
  15. package/docs//345/217/221/347/211/210/346/270/205/345/215/225.md +167 -0
  16. package/docs//345/233/236/346/273/232/351/242/204/346/241/210.md +78 -0
  17. package/docs//345/256/230/346/226/271/346/216/245/345/217/243/351/231/220/345/210/266.md +375 -0
  18. package/docs//345/256/277/344/270/273/345/215/217/350/256/256v1.md +402 -0
  19. package/docs//345/270/270/350/247/201/351/227/256/351/242/230.md +559 -0
  20. package/docs//346/217/222/344/273/266/345/215/217/350/256/256.md +521 -0
  21. package/docs//346/217/222/344/273/266/345/274/200/345/217/221/350/247/204/350/214/203.md +1857 -0
  22. package/docs//346/235/203/351/231/220/346/250/241/345/236/213.md +237 -0
  23. package/docs//346/236/266/346/236/204/350/257/264/346/230/216.md +311 -0
  24. package/docs//347/234/237/346/234/272/350/201/224/350/260/203.md +253 -0
  25. package/docs//351/205/215/347/275/256/345/217/202/350/200/203.md +427 -0
  26. package/package.json +4 -3
  27. package/src/api.js +242 -77
  28. package/src/bot.js +93 -2
  29. package/src/config.js +150 -6
  30. package/src/endpoints.js +5 -3
  31. package/src/ext-deps.js +703 -0
  32. package/src/host/dispatch.js +125 -0
  33. package/src/host/index.js +395 -0
  34. package/src/host/media.js +462 -0
  35. package/src/host/methods.js +756 -0
  36. package/src/host/ops.js +462 -0
  37. package/src/host/serialize.js +79 -0
  38. package/src/host/server.js +397 -0
  39. package/src/instance.js +75 -13
  40. package/src/ledger.js +45 -0
  41. package/src/main.js +5 -1
  42. package/src/onebot/actions.js +524 -0
  43. package/src/onebot/capability.js +95 -0
  44. package/src/onebot/ids.js +265 -0
  45. package/src/onebot/index.js +410 -0
  46. package/src/onebot/segments.js +195 -0
  47. package/src/onebot/translate.js +219 -0
  48. package/src/onebot/voice.js +449 -0
  49. package/src/onebot/ws-server.js +270 -0
  50. package/src/plugin/loader.js +9 -0
  51. package/src/plugin/market.js +19 -0
  52. package/src/web/server.js +408 -1
  53. package/web/app.js +613 -0
  54. package/web/index.html +190 -1
  55. package/web/style.css +69 -0
@@ -0,0 +1,397 @@
1
+ /**
2
+ * 宿主协议 v1 传输层(WS + HTTP + SSE 同端口)
3
+ * ===========================================
4
+ *
5
+ * 一个 `http.Server` 同时处理:
6
+ * POST /rpc 一问一答调一个方法(curl 可测)
7
+ * GET /events SSE 事件流(只推,给不方便用 WS 的客户端 / 抓包排查)
8
+ * GET /ws WS 升级,双向帧(主通道)
9
+ * GET /health 探活,免 token
10
+ *
11
+ * `ws` 模块由调用方用 `deps.load('ws')` 传进来,**不静态 import**。
12
+ * 没装时 `state = 'missing-deps'`,机器人本体照常跑(见 index.js)。
13
+ *
14
+ * 顺序保证:`attach()` 必须同步执行完「注册 sink + 生成 welcome + 补拉」。
15
+ * JS 单线程下这一步中间不会插入 broadcast,所以补拉和实时推送既不会
16
+ * 重复也不会漏——这也是 onHello 不做成 async 的原因。
17
+ */
18
+
19
+ import http from 'node:http';
20
+ import crypto from 'node:crypto';
21
+ import { createLogger } from '../logger.js';
22
+
23
+ const log = createLogger('host-ws');
24
+
25
+ /** 单条报文上限:方法参数里可能带图片 base64,给到 1 MiB */
26
+ const MAX_PAYLOAD = 1024 * 1024;
27
+ const PING_MS = 30_000;
28
+
29
+ /** 与 onebot/ws-server.js 同一套比较方式:长度不等先拒,等长再定时安全比较 */
30
+ function tokenOk(given, want) {
31
+ if (!want) return true;
32
+ const a = Buffer.from(String(given ?? ''));
33
+ const b = Buffer.from(String(want));
34
+ if (a.length !== b.length) return false;
35
+ return crypto.timingSafeEqual(a, b);
36
+ }
37
+
38
+ function tokenOf(req, url) {
39
+ const q = url?.searchParams?.get('access_token');
40
+ if (q) return q;
41
+ const m = /^Bearer\s+(.+)$/i.exec(String(req.headers?.authorization ?? ''));
42
+ return m ? m[1] : '';
43
+ }
44
+
45
+ function sendJson(res, code, body) {
46
+ res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8' });
47
+ res.end(JSON.stringify(body));
48
+ }
49
+
50
+ /** SSE 文本帧:`id` 只在事件帧上给,浏览器重连会把它放进 Last-Event-ID */
51
+ function sseOf(frame) {
52
+ const id = Number.isFinite(frame?.seq) ? `id: ${frame.seq}\n` : '';
53
+ const ev = frame?.type === 'event' ? (frame.event || 'event') : (frame?.type || 'message');
54
+ return `${id}event: ${ev}\ndata: ${JSON.stringify(frame)}\n\n`;
55
+ }
56
+
57
+ /**
58
+ * @param {object} p
59
+ * @param {string} p.host
60
+ * @param {number} p.port
61
+ * @param {string} p.token
62
+ * @param {object|null} p.ws `ws` 模块本身;null 表示只开 HTTP
63
+ * @param {number} [p.maxConnections]
64
+ * @param {(sink:object, info:object)=>{welcome:object, frames:object[]}} p.attach
65
+ * @param {(frame:object, ctx:object)=>Promise<object>} p.onRpc
66
+ * @param {()=>object} p.health
67
+ */
68
+ export function createHostServer({
69
+ host,
70
+ port,
71
+ token,
72
+ ws: wsMod,
73
+ maxConnections = 4,
74
+ attach,
75
+ onRpc,
76
+ health = () => ({}),
77
+ }) {
78
+ /** id → {send(obj), close()};WS 与 SSE 共用一份,broadcast 不区分 */
79
+ const sinks = new Map();
80
+ let nextId = 0;
81
+
82
+ const atCapacity = () => sinks.size >= Math.max(1, Number(maxConnections) || 4);
83
+
84
+ const server = http.createServer(async (req, res) => {
85
+ const url = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`);
86
+
87
+ if (req.method === 'GET' && url.pathname === '/health') {
88
+ return sendJson(res, 200, { app: 'roost-host', protocol: 1, ok: true, ...health() });
89
+ }
90
+
91
+ /** 不设任何 CORS 头;带 Origin 且不同源直接拒,别让网页拿本地 token 乱调 */
92
+ const origin = String(req.headers?.origin ?? '');
93
+ if (origin) {
94
+ try {
95
+ if (new URL(origin).host !== String(req.headers.host ?? '')) {
96
+ return sendJson(res, 403, { ok: false, error: { code: 'FORBIDDEN', message: '跨源请求被拒绝' } });
97
+ }
98
+ } catch {
99
+ return sendJson(res, 403, { ok: false, error: { code: 'FORBIDDEN', message: 'Origin 不合法' } });
100
+ }
101
+ }
102
+ if (!tokenOk(tokenOf(req, url), token)) {
103
+ return sendJson(res, 401, {
104
+ ok: false,
105
+ error: { code: 'UNAUTHORIZED', message: 'access token 不对' },
106
+ });
107
+ }
108
+
109
+ if (req.method === 'GET' && url.pathname === '/') {
110
+ return sendJson(res, 200, {
111
+ app: 'roost-host', protocol: 1, ok: true,
112
+ endpoints: ['POST /rpc', 'GET /events', 'GET /health']
113
+ .concat(wss ? ['GET /ws'] : []),
114
+ });
115
+ }
116
+
117
+ /* ---------------- SSE ---------------- */
118
+ if (req.method === 'GET' && url.pathname === '/events') {
119
+ if (atCapacity()) return sendJson(res, 503, { ok: false, error: { code: 'BUSY', message: '连接数已满' } });
120
+ const since = Number(url.searchParams.get('since') ?? req.headers['last-event-id'] ?? 0) || 0;
121
+ res.writeHead(200, {
122
+ 'Content-Type': 'text/event-stream; charset=utf-8',
123
+ 'Cache-Control': 'no-cache, no-transform',
124
+ Connection: 'keep-alive',
125
+ 'X-Accel-Buffering': 'no',
126
+ });
127
+ res.write(': roost-host/1\n\n');
128
+
129
+ const id = ++nextId;
130
+ const sink = {
131
+ send: (frame) => {
132
+ try {
133
+ res.write(sseOf(frame));
134
+ } catch {
135
+ /* 对端断了,close 事件会清掉 */
136
+ }
137
+ },
138
+ close: () => res.end(),
139
+ };
140
+ /** attach 同步返回:注册 + welcome + 补拉一气呵成,中间不会插进实时事件 */
141
+ const { welcome, frames } = attach(sink, {
142
+ id, since, via: 'sse', peer: String(req.socket?.remoteAddress ?? ''),
143
+ });
144
+ sinks.set(id, sink);
145
+ sink.send({ type: 'welcome', ...welcome });
146
+ for (const f of frames) sink.send(f);
147
+
148
+ req.on('close', () => sinks.delete(id));
149
+ return;
150
+ }
151
+
152
+ /* ---------------- HTTP RPC ---------------- */
153
+ if (req.method === 'POST' && url.pathname === '/rpc') {
154
+ let body = '';
155
+ for await (const chunk of req) {
156
+ body += chunk;
157
+ if (body.length > MAX_PAYLOAD) {
158
+ res.writeHead(413).end();
159
+ return;
160
+ }
161
+ }
162
+ let payload;
163
+ try {
164
+ payload = body.trim() ? JSON.parse(body) : {};
165
+ } catch {
166
+ return sendJson(res, 400, {
167
+ id: '', ok: false,
168
+ error: { code: 'BAD_REQUEST', message: '请求体不是合法 JSON' },
169
+ });
170
+ }
171
+ const out = await onRpc(
172
+ { id: payload?.id ?? '', method: payload?.method, params: payload?.params ?? {} },
173
+ { via: 'http', peer: String(req.socket?.remoteAddress ?? '') },
174
+ );
175
+ return sendJson(res, Number(out.http) || 200, {
176
+ id: out.id ?? '',
177
+ ok: Boolean(out.ok),
178
+ ...(out.ok ? { data: out.data ?? null } : { error: out.error }),
179
+ });
180
+ }
181
+
182
+ sendJson(res, 404, { ok: false, error: { code: 'NOT_FOUND', message: '没有这个端点' } });
183
+ });
184
+
185
+ /* ---------------- WebSocket(可选) ---------------- */
186
+ let wss = null;
187
+ /**
188
+ * 没有 `ws` 时**明确拒绝** upgrade,而不是什么都不挂。
189
+ *
190
+ * 不挂 handler 时 Node 会直接把 socket 丢掉,客户端只看到「连接被关闭」,
191
+ * 完全不知道原因(是没装依赖?token 错?端口错?)。这里回一条 426 并
192
+ * 指明改用 `/events`,让排障有据可依。
193
+ */
194
+ if (!wsMod?.WebSocketServer) {
195
+ server.on('upgrade', (_req, socket) => {
196
+ try {
197
+ socket.write(
198
+ 'HTTP/1.1 426 Upgrade Required\r\n'
199
+ + 'Connection: close\r\n'
200
+ + 'Content-Type: text/plain; charset=utf-8\r\n'
201
+ + '\r\n'
202
+ + '这台 Roost 没装 ws 依赖,/ws 不可用;请改用 POST /rpc + GET /events(SSE)。\n',
203
+ );
204
+ } catch { /* socket 可能已断 */ }
205
+ socket.destroy();
206
+ });
207
+ }
208
+ if (wsMod?.WebSocketServer) {
209
+ wss = new wsMod.WebSocketServer({ noServer: true, maxPayload: MAX_PAYLOAD, perMessageDeflate: false });
210
+ server.on('upgrade', (req, socket, head) => {
211
+ const url = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`);
212
+ if (!['/', '/ws'].includes(url.pathname)) {
213
+ socket.write('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n');
214
+ socket.destroy();
215
+ return;
216
+ }
217
+ const origin = String(req.headers?.origin ?? '');
218
+ if (origin) {
219
+ try {
220
+ if (new URL(origin).host !== String(req.headers.host ?? '')) {
221
+ socket.write('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n');
222
+ socket.destroy();
223
+ return;
224
+ }
225
+ } catch {
226
+ socket.destroy();
227
+ return;
228
+ }
229
+ }
230
+ if (!tokenOk(tokenOf(req, url), token)) {
231
+ socket.write('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n');
232
+ socket.destroy();
233
+ return;
234
+ }
235
+ wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req));
236
+ });
237
+
238
+ wss.on('connection', (ws) => {
239
+ if (atCapacity()) {
240
+ try {
241
+ ws.close(1013, 'too many connections');
242
+ } catch {
243
+ /* 忽略 */
244
+ }
245
+ return;
246
+ }
247
+ ws.isAlive = true;
248
+ ws.on('pong', () => {
249
+ ws.isAlive = true;
250
+ });
251
+ ws.on('error', (e) => log.warn(`连接异常:${e.message}`));
252
+
253
+ const id = ++nextId;
254
+ let attached = null;
255
+ const sink = {
256
+ send: (frame) => {
257
+ if (ws.readyState !== 1) return;
258
+ try {
259
+ ws.send(JSON.stringify(frame));
260
+ } catch (e) {
261
+ log.warn(`推送失败:${e.message}`);
262
+ }
263
+ },
264
+ close: () => {
265
+ try {
266
+ ws.close(1001, 'server closing');
267
+ } catch {
268
+ /* 忽略 */
269
+ }
270
+ },
271
+ };
272
+
273
+ ws.on('message', async (raw) => {
274
+ let f;
275
+ try {
276
+ f = JSON.parse(String(raw));
277
+ } catch {
278
+ sink.send({ type: 'res', id: '', ok: false, error: { code: 'BAD_REQUEST', message: '报文不是合法 JSON' } });
279
+ return;
280
+ }
281
+ const type = String(f?.type ?? '');
282
+
283
+ if (type === 'hello' || type === 'req') {
284
+ /** 第一个 hello/req 都算握手:先注册,避免漏掉握手期间的事件 */
285
+ if (!attached) {
286
+ const since = Number(f.since ?? 0) || 0;
287
+ const got = attach(sink, {
288
+ id, since, via: 'ws', peer: String(ws._socket?.remoteAddress ?? ''),
289
+ client: String(f.client ?? ''),
290
+ protocol: Number(f.protocol ?? 0),
291
+ });
292
+ attached = got;
293
+ sinks.set(id, sink);
294
+ sink.send({ type: 'welcome', ...got.welcome });
295
+ for (const frame of got.frames) sink.send(frame);
296
+ }
297
+ if (type === 'hello') return;
298
+ }
299
+
300
+ if (type === 'req') {
301
+ const out = await onRpc(
302
+ { id: f.id ?? '', method: f.method, params: f.params ?? {} },
303
+ { via: 'ws', clientId: id, peer: String(ws._socket?.remoteAddress ?? '') },
304
+ );
305
+ sink.send({
306
+ type: 'res', id: out.id ?? '', ok: Boolean(out.ok),
307
+ ...(out.ok ? { data: out.data ?? null } : { error: out.error }),
308
+ });
309
+ return;
310
+ }
311
+ if (type === 'ping') {
312
+ sink.send({ type: 'pong', at: Date.now() });
313
+ return;
314
+ }
315
+ if (!attached) {
316
+ sink.send({ type: 'res', id: f.id ?? '', ok: false, error: { code: 'BAD_REQUEST', message: '先发 hello' } });
317
+ }
318
+ });
319
+
320
+ ws.on('close', () => sinks.delete(id));
321
+ });
322
+ }
323
+
324
+ const pinger = setInterval(() => {
325
+ if (!wss) return;
326
+ for (const ws of wss.clients) {
327
+ if (ws.isAlive === false) {
328
+ ws.terminate();
329
+ continue;
330
+ }
331
+ ws.isAlive = false;
332
+ try {
333
+ ws.ping();
334
+ } catch {
335
+ /* 下一轮 terminate */
336
+ }
337
+ }
338
+ }, PING_MS);
339
+ pinger.unref?.();
340
+
341
+ return {
342
+ get port() {
343
+ return server.address()?.port ?? port;
344
+ },
345
+ get connections() {
346
+ return sinks.size;
347
+ },
348
+ broadcast(frame) {
349
+ for (const sink of sinks.values()) sink.send(frame);
350
+ },
351
+ start() {
352
+ return new Promise((resolve, reject) => {
353
+ const onError = (e) => {
354
+ server.removeListener('listening', onListening);
355
+ reject(e);
356
+ };
357
+ const onListening = () => {
358
+ server.removeListener('error', onError);
359
+ resolve(server.address()?.port ?? port);
360
+ };
361
+ server.once('error', onError);
362
+ server.once('listening', onListening);
363
+ server.listen(port, host);
364
+ });
365
+ },
366
+ async stop() {
367
+ clearInterval(pinger);
368
+ for (const sink of sinks.values()) sink.close();
369
+ sinks.clear();
370
+ if (wss) {
371
+ const hard = setTimeout(() => {
372
+ for (const ws of wss.clients) {
373
+ try {
374
+ ws.terminate();
375
+ } catch {
376
+ /* 已经关了 */
377
+ }
378
+ }
379
+ }, 600);
380
+ hard.unref?.();
381
+ await new Promise((resolve) => wss.close(() => resolve()));
382
+ clearTimeout(hard);
383
+ }
384
+ await new Promise((resolve) => {
385
+ const t = setTimeout(() => {
386
+ server.closeAllConnections?.();
387
+ resolve();
388
+ }, 2000);
389
+ t.unref?.();
390
+ server.close(() => {
391
+ clearTimeout(t);
392
+ resolve();
393
+ });
394
+ });
395
+ },
396
+ };
397
+ }
package/src/instance.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import fs from 'node:fs/promises';
2
- import { readFileSync, statSync } from 'node:fs';
2
+ import { readFileSync, readlinkSync, statSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { execFileSync } from 'node:child_process';
5
5
  import { createHash } from 'node:crypto';
@@ -155,6 +155,37 @@ function looksLikeNodeRuntime(name) {
155
155
  return /\bnode\b|electron|.*harness.*/i.test(base);
156
156
  }
157
157
 
158
+ /**
159
+ * 纯函数:`/proc/<pid>` 的三处内容里,有没有证据表明它是 node 运行时。
160
+ *
161
+ * **为什么不能只看 `comm`**:Node 24 起会把主线程名设成 `MainThread`,
162
+ * `/proc/<pid>/comm` 读出来就是这四个字,不再含 `node`。只认 comm 会把一个
163
+ * **活着的**实例判成陈旧记录 → 删锁 → 放行第二次认领 → 同 AppID 双开 →
164
+ * 4902 互踢。CI 的 `ubuntu-latest / Node 24.x` 就是从这条断言红起的。
165
+ *
166
+ * 判定顺序(与文件头「拿不准往活着倒」一致):
167
+ * · `comm` 读不到(空串)→ 活(无法确认就不否定)
168
+ * · comm / cmdline / exe 任一提及 node → 活
169
+ * · **另两项一个都没读到**(传 `null`)→ 活
170
+ * · 至少读到一项、且都没提 node → 死(这才真的是 PID 被别的程序复用)
171
+ *
172
+ * 倒数第二条是**跨用户 / 加固内核**的保命线:`/proc/<pid>/exe` 要 ptrace 权限,
173
+ * 读别人的进程会 EACCES;`cmdline` 在非 dumpable 进程上也可能读不到。
174
+ * 若这时只拿 comm 下结论,一个 `MainThread` 的活实例就会被判死——又绕回互踢。
175
+ * 「读不到」和「读到了但没有 node」必须分开,所以这里用 `null` 表示前者。
176
+ *
177
+ * 拆成纯函数是为了能在**任意平台**单测:真机上只有跑在对应系统上才能观测到
178
+ * `/proc` 的内容,而这段逻辑恰恰是跨平台行为分叉的地方。
179
+ */
180
+ function looksLikeNodeProc({ comm = '', cmdline = null, exe = null } = {}) {
181
+ if (!comm) return true;
182
+ if (/node/i.test(comm)) return true;
183
+ if (cmdline && /node/i.test(cmdline)) return true;
184
+ if (exe && /node/i.test(exe)) return true;
185
+ if (cmdline === null && exe === null) return true;
186
+ return false;
187
+ }
188
+
158
189
  /**
159
190
  * 这个 pid 现在是不是一个 node 进程。
160
191
  *
@@ -193,15 +224,16 @@ function pidLooksLikeNode(pid) {
193
224
  if (process.platform === 'linux') {
194
225
  const comm = readFileSync(`/proc/${pid}/comm`, 'utf8').trim();
195
226
  /**
196
- * 读到空字符串时**按活着算**,不是按死了算。
197
- *
198
- * 判断不出来的方向要选保守的那个:当成死 → 删记录 → 放行第二次认领
199
- * → 同一个 AppID 双开 → 4902 互踢,正是这套机制存在的理由。
200
- * 当成活 → 顶多让用户手动清一条残留记录(有 `--force`)。
201
- *
202
- * 真实的误判代价不对称,所以拿不准就往"活着"倒。
227
+ * Node 24 起主线程被改名成 `MainThread`,`comm` 不再含 `node`,
228
+ * 所以再核对 `cmdline`(完整命令行)与 `exe`(可执行文件链接)。
229
+ * **读不到的项传 `null`**(不是空串):纯函数要区分「这一项没证据」和
230
+ * 「这一项读不到」,后者在跨用户 / 加固内核下很常见,不能单独导致判死。
203
231
  */
204
- return comm ? /node/i.test(comm) : true;
232
+ let cmdline = null;
233
+ let exe = null;
234
+ try { cmdline = readFileSync(`/proc/${pid}/cmdline`, 'utf8').replace(/\0/g, ' '); } catch { /* 读不到就看下一项 */ }
235
+ try { exe = readlinkSync(`/proc/${pid}/exe`); } catch { /* 权限或已退出 */ }
236
+ return looksLikeNodeProc({ comm, cmdline, exe });
205
237
  }
206
238
  const comm = execFileSync('ps', ['-p', String(pid), '-o', 'comm='], {
207
239
  encoding: 'utf8',
@@ -332,8 +364,20 @@ const ROOST_HINT = /(qq-bot-roost|src[\\/]main\.js)/i;
332
364
  */
333
365
  async function isOurRoost(pid, rec = null) {
334
366
  const beat = rec ? beatAlive(rec) : null;
335
- /** 心跳新鲜:不用再问进程名 / wmic / PowerShell,直接判活 */
336
- if (beat === true) return true;
367
+ /**
368
+ * 心跳新鲜:不用再问进程名 / wmic / PowerShell,**但仍要问 pid 在不在**。
369
+ *
370
+ * 心跳文件是「最后一个活着的那次心跳」——进程被强杀(关 DSH、任务管理器、
371
+ * 断点调试)时它不会自己消失,mtime 就停在死的那一刻。30 秒租约内重启,
372
+ * 新进程会撞上自己**前一条**记录:心跳还新鲜 → 判活 → 拒绝认领 →
373
+ * 机器人直接 `error`。2026-11-13 实机踩到:心跳停在 08:52:15,08:52:34
374
+ * 认领被判「AppID 被 PID 28256 占用」,而 28256 早就没了。
375
+ *
376
+ * pid 不存在 ⇒ 进程一定没了(进程退出时 pid 就被释放,系统不会把「不存在」
377
+ * 复用出去),所以这一眼不算贵、也不破坏「拿不准往活着倒」:
378
+ * `pidExists` 遇到 EPERM(跨用户、权限不足)返回 true,仍然保守判活。
379
+ */
380
+ if (beat === true) return pidExists(pid);
337
381
  /** 有租约的记录只看 pid 是否存在;升级前的旧记录沿用含进程名的 isAlive */
338
382
  const exists = beat === null ? isAlive(pid) : pidExists(pid);
339
383
  if (!exists) return false;
@@ -398,9 +442,17 @@ function prune(data) {
398
442
  for (const [key, rec] of Object.entries(data)) {
399
443
  if (!rec) continue;
400
444
  const beat = beatAlive(rec);
401
- /** 心跳新鲜就是活,连 pid 都不用看——PID 被复用也挡得住 */
445
+ /**
446
+ * 心跳新鲜 + pid 还在才算活。
447
+ *
448
+ * 光看心跳会被**残留心跳**骗:进程被强杀后心跳文件留在原地,mtime 停在
449
+ * 死亡时刻,30 秒内看起来「刚刚还在跳」。那段时间里重启必然撞上自己这条
450
+ * 记录(详见 `isOurRoost` 里的同日实测),所以这里多问一眼 pid。
451
+ * PID 被复用挡不住也没关系——复用意味着 pid 存在,这里只负责剪掉
452
+ * 「pid 根本不存在」的确定性死记录,细判仍交给冲突路径。
453
+ */
402
454
  if (beat === true) {
403
- out[key] = rec;
455
+ if (pidExists(rec.pid)) out[key] = rec;
404
456
  continue;
405
457
  }
406
458
  if (beat === false) {
@@ -594,6 +646,16 @@ export function _pidExists(pid) {
594
646
  return pidExists(pid);
595
647
  }
596
648
 
649
+ /**
650
+ * 测试用:`/proc/<pid>` 三处证据的合并判据。
651
+ *
652
+ * 这条逻辑跨平台分叉,真机上只有跑在对应系统才观测得到 `/proc` 的内容,
653
+ * 所以在 CI 里用表驱动直接喂 comm / cmdline / exe(见 `test/instance-proc.mjs`)。
654
+ */
655
+ export function _looksLikeNodeProc(parts) {
656
+ return looksLikeNodeProc(parts);
657
+ }
658
+
597
659
  /** 测试用:直接跑剪枝,便于构造「停跳租约 + 不像 node 的进程名」边界 */
598
660
  export function _pruneForTest(data) {
599
661
  return prune(data);
package/src/ledger.js CHANGED
@@ -470,6 +470,51 @@ export class EventLedger {
470
470
  return rows.reverse().map(mapRow);
471
471
  }
472
472
 
473
+ /**
474
+ * 某会话的最近 N 条**带原始报文**的历史。
475
+ *
476
+ * 和 `recent()` 的区别:这个把 `payload` 也取出来,用于「模拟历史消息接口」——
477
+ * OneBot 的 `get_group_msg_history` 要还原消息段(图片、语音、引用),
478
+ * 只靠 `content` 会把图片全丢掉。
479
+ *
480
+ * 只给内部用(OneBot 兼容层),面板仍然走 `recent()`——那边不需要 payload,
481
+ * 少传一份大字段。
482
+ *
483
+ * @param {object} p
484
+ * @param {string} p.chatId
485
+ * @param {number} [p.limit]
486
+ * @param {number} [p.beforeSeq]
487
+ */
488
+ history({ chatId, limit = 20, beforeSeq } = {}) {
489
+ if (!this.available || this.closed || !chatId) return [];
490
+ const lim = Math.min(Math.max(Number(limit) || 20, 1), 200);
491
+ const rows = beforeSeq
492
+ ? this.db
493
+ .prepare(
494
+ `SELECT seq, id, kind, chat_id, user_id, user_name, content, at, msg_idx, quoted, payload
495
+ FROM events WHERE bot_id = ? AND chat_id = ? AND seq < ?
496
+ ORDER BY seq DESC LIMIT ?`,
497
+ )
498
+ .all(this.botId, String(chatId), Number(beforeSeq), lim)
499
+ : this.db
500
+ .prepare(
501
+ `SELECT seq, id, kind, chat_id, user_id, user_name, content, at, msg_idx, quoted, payload
502
+ FROM events WHERE bot_id = ? AND chat_id = ?
503
+ ORDER BY seq DESC LIMIT ?`,
504
+ )
505
+ .all(this.botId, String(chatId), lim);
506
+
507
+ return rows.reverse().map((r) => {
508
+ let payload = null;
509
+ try {
510
+ payload = JSON.parse(r.payload ?? '{}');
511
+ } catch {
512
+ payload = null;
513
+ }
514
+ return { ...mapRow(r), payload };
515
+ });
516
+ }
517
+
473
518
  /**
474
519
  * 某个人说过的话(跨会话)。
475
520
  *
package/src/main.js CHANGED
@@ -197,7 +197,11 @@ function registerCoreCommands(rt) {
197
197
  return out;
198
198
  };
199
199
 
200
- const pluginMenus = [...registry.menus.values()].filter((m) => m.id !== '__core');
200
+ /**
201
+ * 独占模式(OneBot 兼容)下插件不回话,菜单里也就别再列它们——
202
+ * 列出来点了没反应,比不显示更让人困惑。内核命令照常列(绑定就在这里)。
203
+ */
204
+ const pluginMenus = msg.coreOnly ? [] : [...registry.menus.values()].filter((m) => m.id !== '__core');
201
205
 
202
206
  /* ---------- 有参数:进下级 ---------- */
203
207
  if (arg) {