qq-bot-roost 1.0.16-beta.1 → 1.0.16

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 CHANGED
@@ -8,9 +8,9 @@
8
8
 
9
9
  <img src="https://img.shields.io/badge/Node.js-22.13%2B-339933?logo=node.js&logoColor=white" alt="Node.js 22.13+">
10
10
  <img src="https://img.shields.io/badge/dependencies-0-brightgreen" alt="零依赖">
11
- <img src="https://img.shields.io/badge/tests-1034%20passed-brightgreen" alt="测试 1034 项">
11
+ <img src="https://img.shields.io/badge/tests-1079%20passed-brightgreen" alt="测试 1079 项">
12
12
  <img src="https://img.shields.io/badge/plugins-JS%20%7C%20Python%20%7C%20Go%20%7C%20any-blue" alt="多语言插件">
13
- <img src="https://img.shields.io/badge/version-1.0.16--beta.1-blueviolet" alt="版本 1.0.16-beta.1">
13
+ <img src="https://img.shields.io/badge/version-1.0.16-blueviolet" alt="版本 1.0.16">
14
14
  <img src="https://img.shields.io/badge/license-AGPL--3.0--only-blue" alt="AGPL-3.0-only">
15
15
  <a href="https://github.com/tdcq9594/qq-bot-roost/actions"><img src="https://img.shields.io/github/actions/workflow/status/tdcq9594/qq-bot-roost/ci.yml?branch=master" alt="CI"></a>
16
16
 
@@ -230,6 +230,9 @@ data: {"at":1731400000000}
230
230
  | | `plugin.data.*` / `plugin.groups.*` | read ~ manage | 插件存档、按群开关 |
231
231
  | | `plugin.market` / `plugin.versions` / `plugin.updates` | read | 市场、本地版本、可更新 |
232
232
  | | `plugin.install/remove/update/update.all/rescan/load/unload/forget` | manage | 插件全生命周期 |
233
+ | 扩展联动 | `ext.list` | read | 列出 DSH 已装扩展暴露的动作 |
234
+ | | `ext.call` | message | 调一个扩展动作(SSE 请求 + RPC 回执) |
235
+ | | `ext.register` / `ext.call.reply` | message | DSH 上报清单 / 回传结果(内部) |
233
236
  | 配置 | `config.get` | read | 脱敏后的机器人配置 |
234
237
  | | `config.set` | manage | 改运行时设置(见下) |
235
238
 
@@ -400,3 +403,33 @@ data: {"at":1731400000000}
400
403
 
401
404
  两个出口**共用同一份 `ws` 依赖与同一张「依赖」卡片**:装一次,两边都能用。
402
405
  外接页上半部分是宿主协议,下半部分仍是 OneBot。
406
+
407
+ ## 7. 反向联动:框架插件 → DSH 扩展
408
+
409
+ `tool.*` 解决的是「DSH 调框架插件工具」,方向是客户端到服务端。反过来
410
+ 「框架插件调 DSH 已装扩展」需要一条回程,但不新开端口、不给 DSH 发第二套
411
+ 令牌——复用协议已有的两条通道:
412
+
413
+ ```
414
+ 框架插件 ctx.ext.call('bili', 'refresh_hot')
415
+ │
416
+ ├─ ext.call 方法 → 生成 requestId → SSE 事件 ext.call.request ──► DSH
417
+ │ │
418
+ │ DSH 按 ui.actions 白名单执行进程内动作
419
+ │ │
420
+ ◄──────────── RPC ext.call.reply {requestId, result} ──────────┘
421
+ │
422
+ └─ pending Promise resolve → 结果回到插件
423
+ ```
424
+
425
+ - 能力清单由 DSH 连上后调 `ext.register` 上报,内容直接取自扩展
426
+ `plugin.json` 的 `ui.actions`,**不新增声明格式**;只有
427
+ `ui.runtime: "inprocess"` 的扩展能被同步调用(MCP 子进程的 stdin 管道
428
+ 不属于宿主)。
429
+ - 每个请求带 30 秒超时;认不出的 `requestId` 一律拒绝,防止旧回执解掉新
430
+ 请求;协议停止时 `clear()` 把还在等的调用全部解掉,插件不会挂在 `await` 上。
431
+ - 框架插件侧入口是 `ctx.ext.list()` / `ctx.ext.call(extId, action, payload)`;
432
+ 没接外接协议时 `available === false`,`call()` 明确抛错,不静默失败。
433
+ - DSH 侧对外同样提供 `GET /v1/roost.capabilities` 与 `POST /v1/roost.call`:
434
+ 扩展可经宿主代理调用只读能力、框架插件的 `tool.*` 与 `msg.send`,
435
+ 框架地址与令牌不出宿主,写/管理面不开放。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qq-bot-roost",
3
- "version": "1.0.16-beta.1",
3
+ "version": "1.0.16",
4
4
  "type": "module",
5
5
  "description": "栖 Roost:零依赖的 QQ 官方机器人框架,填 AppID/AppSecret 即连,插件可写任意语言",
6
6
  "license": "AGPL-3.0-only",
@@ -29,9 +29,9 @@
29
29
  "start": "node src/main.js",
30
30
  "mock": "node src/main.js --mock",
31
31
  "check": "node src/main.js --check",
32
- "test": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/market-cache.mjs && node --test test/market-kind.mjs && node --test test/instance-proc.mjs && node --test test/proxy.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/reply-auto.mjs && node --test test/plugin-observability.mjs && node --test test/outbound-dry.mjs && node --test test/ext-deps-migrate.mjs && node --test test/onebot-deps.mjs && node --test test/onebot-config.mjs && node --test test/onebot-segments.mjs && node --test test/onebot-outbound-at.mjs && node --test test/onebot-translate.mjs && node --test test/onebot-voice.mjs && node --test test/onebot-loopback.mjs && node --test test/host-protocol.mjs && node --test test/host-config.mjs && node --test test/host-tool-methods.mjs && node --test test/web-token-echo.mjs && node --test test/group-manage.mjs && node --test test/wakeup-payload.mjs && node --test test/typing.mjs && node --test test/media-convert.mjs",
32
+ "test": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/market-cache.mjs && node --test test/market-kind.mjs && node --test test/instance-proc.mjs && node --test test/proxy.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/reply-auto.mjs && node --test test/plugin-observability.mjs && node --test test/outbound-dry.mjs && node --test test/ext-deps-migrate.mjs && node --test test/onebot-deps.mjs && node --test test/onebot-config.mjs && node --test test/onebot-segments.mjs && node --test test/onebot-outbound-at.mjs && node --test test/onebot-translate.mjs && node --test test/onebot-voice.mjs && node --test test/onebot-loopback.mjs && node --test test/host-protocol.mjs && node --test test/host-config.mjs && node --test test/host-tool-methods.mjs && node --test test/host-ext-bridge.mjs && node --test test/web-token-echo.mjs && node --test test/group-manage.mjs && node --test test/wakeup-payload.mjs && node --test test/typing.mjs && node --test test/media-convert.mjs",
33
33
  "test:e2e": "node test/e2e.mjs",
34
- "test:all": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/market-cache.mjs && node --test test/market-kind.mjs && node --test test/instance-proc.mjs && node --test test/proxy.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/reply-auto.mjs && node test/e2e.mjs && node test/live-driver.mjs && node --test test/ext-deps-migrate.mjs && node --test test/onebot-deps.mjs && node --test test/onebot-config.mjs && node --test test/onebot-segments.mjs && node --test test/onebot-outbound-at.mjs && node --test test/onebot-translate.mjs && node --test test/onebot-voice.mjs && node --test test/onebot-loopback.mjs && node --test test/host-protocol.mjs && node --test test/host-config.mjs && node --test test/host-tool-methods.mjs && node --test test/web-token-echo.mjs && node --test test/group-manage.mjs && node --test test/wakeup-payload.mjs && node --test test/typing.mjs && node --test test/media-convert.mjs",
34
+ "test:all": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/market-cache.mjs && node --test test/market-kind.mjs && node --test test/instance-proc.mjs && node --test test/proxy.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/reply-auto.mjs && node test/e2e.mjs && node test/live-driver.mjs && node --test test/ext-deps-migrate.mjs && node --test test/onebot-deps.mjs && node --test test/onebot-config.mjs && node --test test/onebot-segments.mjs && node --test test/onebot-outbound-at.mjs && node --test test/onebot-translate.mjs && node --test test/onebot-voice.mjs && node --test test/onebot-loopback.mjs && node --test test/host-protocol.mjs && node --test test/host-config.mjs && node --test test/host-tool-methods.mjs && node --test test/host-ext-bridge.mjs && node --test test/web-token-echo.mjs && node --test test/group-manage.mjs && node --test test/wakeup-payload.mjs && node --test test/typing.mjs && node --test test/media-convert.mjs",
35
35
  "check:secrets": "node scripts/check-secrets.mjs",
36
36
  "create": "node scripts/create-plugin.mjs",
37
37
  "test:plugin": "node scripts/test-plugin.mjs",
package/src/api.js CHANGED
@@ -185,7 +185,27 @@ export function buildSendPayload(opts = {}, nextSeq = () => 1) {
185
185
  * 留着空串跟「类型与内容不匹配」(22006)只差一步。
186
186
  */
187
187
  if (card) {
188
- payload.card = card;
188
+ /**
189
+ * 官方 msg_type=8 的 `card` 必须是
190
+ * `{type:'tuwen', content:{title, description, url, pic_url}}`。
191
+ *
192
+ * 但协议 / 扩展路径(`/v1/roost.call` → `msg.send`、`/v1/send`)给的
193
+ * 一直是扁平四字段 `{title, description, url, picUrl}`;直接透传官方回
194
+ * `card msg is nil`,消息根本发不出去,面板上就是「点了没反应」。
195
+ * `msg.replyTuwen()` 早已构造好嵌套结构,这里只补扁平那一种。
196
+ */
197
+ const normalized = card?.type === 'tuwen' && card?.content && typeof card.content === 'object'
198
+ ? card
199
+ : {
200
+ type: 'tuwen',
201
+ content: {
202
+ title: String(card?.title ?? ''),
203
+ description: String(card?.description ?? ''),
204
+ url: String(card?.url ?? ''),
205
+ pic_url: String(card?.picUrl ?? card?.pic_url ?? ''),
206
+ },
207
+ };
208
+ payload.card = normalized;
189
209
  payload.msg_type = 8;
190
210
  payload.content = '';
191
211
  }
package/src/bot.js CHANGED
@@ -303,6 +303,8 @@ export class BotRuntime {
303
303
  /** 身份对照表:插件通过 ctx.identity 只读查询(QQ号 → openid) */
304
304
  identity: this.identity,
305
305
  isOwner: (uid) => cfg.owners.includes(uid),
306
+ /** 外接协议桥:给插件 `ctx.ext.*`,让它能调 DSH 侧已装扩展的能力 */
307
+ host: this.host,
306
308
  // 插件声明了 frameworkVersion 就做兼容校验;作者本地调试可以关掉
307
309
  ignoreCompat: this.globalCfg.plugins?.ignoreFrameworkVersion === true,
308
310
  });
@@ -0,0 +1,140 @@
1
+ /**
2
+ * 框架插件 ↔ DSH 扩展:反向调用桥
3
+ * ================================
4
+ *
5
+ * 直连协议(roost-host/1)里 DSH 是客户端、框架是服务端,所以「扩展调框架
6
+ * 插件工具」天然走得通(`tool.*`);反过来「框架插件调扩展」需要一条回程。
7
+ *
8
+ * 不新开端口、不给 DSH 发令牌:复用协议已有的两条通道——
9
+ *
10
+ * 框架 --SSE 事件 `ext.call.request`--> DSH
11
+ * 框架 <--HTTP RPC `ext.call.reply`-- DSH
12
+ *
13
+ * 这一层只管「请求 → 等回执」的配对,是纯逻辑,不碰网络:
14
+ *
15
+ * · 每个请求一个 id,带超时(DSH 没连上 / 扩展卡住都要能失败,不能挂死);
16
+ * · 回执只能认自己发出去的 id,杜绝别的客户端伪造结果;
17
+ * · 能力清单由 DSH 连上后上报(`ext.register`),框架不主动扫盘。
18
+ *
19
+ * 为什么扩展能力不投影成 `tool.*`:`tool.*` 的 scope 是 `message`,谁拿到
20
+ * 协议令牌都能调;而扩展动作可能带写操作(发消息、评论),应当只在框架
21
+ * 插件明确调用时才发生,且由 DSH 自己按 `ui.actions` 白名单把着。
22
+ */
23
+
24
+ import { HostError } from './methods.js';
25
+
26
+ const DEFAULT_TIMEOUT_MS = 30_000;
27
+ const MAX_PENDING = 32;
28
+ const MAX_PAYLOAD_KEYS = 40;
29
+
30
+ export function createExtBridge({ pushEvent = () => {}, timeoutMs = DEFAULT_TIMEOUT_MS, log = () => {} } = {}) {
31
+ /** requestId -> { resolve, reject, timer, at } */
32
+ const pending = new Map();
33
+ /** DSH 上报的扩展能力清单:{ extId, actions:[{id,label}] }[] */
34
+ let catalog = [];
35
+ let catalogAt = 0;
36
+ let seq = 0;
37
+
38
+ function fail(p, e) {
39
+ clearTimeout(p.timer);
40
+ pending.delete(p.id);
41
+ p.reject(e);
42
+ }
43
+
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);
53
+ if (pending.size >= MAX_PENDING) {
54
+ throw new HostError('BUSY', `同时最多 ${MAX_PENDING} 个扩展调用,稍后再试`, 429);
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));
62
+ }
63
+
64
+ const promise = new Promise((resolve, reject) => {
65
+ /**
66
+ * **不要 unref**:这个定时器是请求生命周期本身的一部分。unref 之后
67
+ * 若进程里暂时没有别的活跃 handle(例如框架正在停机、或单测环境),
68
+ * 超时永远不触发,调用方会永久挂在 await 上。停机路径由
69
+ * `HostBridge.#stopNow()` 调 `clear()` 统一解掉,不会拖住退出。
70
+ */
71
+ const timer = setTimeout(() => {
72
+ const p = pending.get(requestId);
73
+ if (p) fail(p, new HostError('TIMEOUT', `扩展 ${id}.${act} 没在 ${timeoutMs}ms 内回执`, 504));
74
+ }, timeoutMs);
75
+ pending.set(requestId, { id: requestId, resolve, reject, timer, at: Date.now() });
76
+ });
77
+
78
+ try {
79
+ pushEvent('ext.call.request', {
80
+ requestId, extId: id, action: act, payload: args,
81
+ /** 调用方所在会话,DSH 侧要按它派生扩展的上下文;可为空 */
82
+ chat: String(chat ?? '').slice(0, 120),
83
+ });
84
+ } catch (e) {
85
+ const p = pending.get(requestId);
86
+ if (p) fail(p, new HostError('INTERNAL', `推不出扩展调用事件:${e?.message ?? e}`, 500));
87
+ }
88
+ return await promise;
89
+ }
90
+
91
+ /** DSH 通过 RPC 回执。认不出 id 一律拒绝,别让旧回执解掉新请求 */
92
+ function reply({ requestId = '', ok = true, result = null, error = '' } = {}) {
93
+ const key = String(requestId ?? '').trim();
94
+ const p = pending.get(key);
95
+ if (!p) throw new HostError('NOT_FOUND', '没有这个待回执的扩展调用(可能已超时)', 404);
96
+ clearTimeout(p.timer);
97
+ pending.delete(key);
98
+ if (ok === false) {
99
+ p.reject(new HostError('EXT_FAILED', String(error ?? '扩展调用失败').slice(0, 300), 502));
100
+ return { ok: true, settled: key, failed: true };
101
+ }
102
+ p.resolve(result ?? null);
103
+ return { ok: true, settled: key };
104
+ }
105
+
106
+ /** DSH 连上 / 扩展装卸后上报能力清单 */
107
+ function register({ extensions = [] } = {}) {
108
+ const list = Array.isArray(extensions) ? extensions : [];
109
+ catalog = list
110
+ .filter((e) => e && typeof e.id === 'string' && e.id)
111
+ .map((e) => ({
112
+ extId: e.id.slice(0, 64),
113
+ actions: (Array.isArray(e.actions) ? e.actions : [])
114
+ .filter((a) => a && typeof a.id === 'string' && a.id)
115
+ .slice(0, 60)
116
+ .map((a) => ({ id: a.id.slice(0, 80), label: String(a.label ?? a.id).slice(0, 120) })),
117
+ }));
118
+ catalogAt = Date.now();
119
+ log(`扩展能力清单已更新:${catalog.length} 个扩展 / ${catalog.reduce((n, e) => n + e.actions.length, 0)} 个动作`);
120
+ return { ok: true, count: catalog.length };
121
+ }
122
+
123
+ return {
124
+ call,
125
+ reply,
126
+ register,
127
+ list: () => ({
128
+ extensions: catalog.map((e) => ({ extId: e.extId, actions: e.actions.map((a) => ({ ...a })) })),
129
+ updatedAt: catalogAt,
130
+ pending: pending.size,
131
+ }),
132
+ /** 断线时把还在等的请求全部解掉,别让框架插件永远挂在 await 上 */
133
+ clear: (why = '链路断开') => {
134
+ for (const p of [...pending.values()]) {
135
+ fail(p, new HostError('DISCONNECTED', `${why},扩展调用已取消`, 503));
136
+ }
137
+ },
138
+ pendingCount: () => pending.size,
139
+ };
140
+ }
package/src/host/index.js CHANGED
@@ -26,6 +26,7 @@ import { createLogger } from '../logger.js';
26
26
  import * as deps from '../ext-deps.js';
27
27
  import { createHostServer } from './server.js';
28
28
  import { createMethods, effectiveScopes, HostError, HOST_PROTOCOL } from './methods.js';
29
+ import { createExtBridge } from './ext-bridge.js';
29
30
  import { serializeMessage, serializeNotice } from './serialize.js';
30
31
 
31
32
  const log = createLogger('host');
@@ -70,10 +71,19 @@ export class HostBridge {
70
71
  * 才知道这个协议能干什么;createMethods 只捕获 runtime 引用,
71
72
  * 里面的 R.api / R.plugins 都是调用时现读,早建不会拿到过期对象。
72
73
  */
74
+ /**
75
+ * 反向调用桥:框架插件调 DSH 扩展。事件走协议自己的 SSE 流,
76
+ * 回执走 RPC,所以不新开监听、不给 DSH 发第二套令牌。
77
+ */
78
+ this.extBridge = createExtBridge({
79
+ pushEvent: (event, data) => this.#push(event, data),
80
+ log: (m) => log.info(`[ext-bridge] ${m}`),
81
+ });
73
82
  this.methods = createMethods({
74
83
  runtime: this.runtime,
75
84
  getState: () => this.#state(),
76
85
  log: (m) => log.info(m),
86
+ extBridge: this.extBridge,
77
87
  });
78
88
  /** 插件工具集签名:变了就往事件流推一条 capabilities.changed */
79
89
  this.toolSig = this.methods?.toolSignature?.() ?? '';
@@ -219,6 +229,8 @@ export class HostBridge {
219
229
  await this.server.stop().catch((e) => log.warn(`关监听失败:${e.message}`));
220
230
  this.server = null;
221
231
  }
232
+ /** 监听关了就没人能回执了,把还在等的扩展调用全部解掉,别挂死插件 */
233
+ this.extBridge?.clear?.('外接协议已停止');
222
234
  if (this.state === 'running') this.state = 'stopped';
223
235
  this.port = 0;
224
236
  return this;
@@ -136,7 +136,7 @@ const scopeForQq = (name) => {
136
136
  * @param {()=>object} p.getState 协议层自己的状态快照
137
137
  * @param {(m:string)=>void} [p.log]
138
138
  */
139
- export function createMethods({ runtime: R, getState, log = () => {} }) {
139
+ export function createMethods({ runtime: R, getState, log = () => {}, extBridge = null }) {
140
140
  const table = new Map();
141
141
  const def = (name, scope, desc, run) => table.set(name, { name, scope, desc, run });
142
142
 
@@ -325,7 +325,20 @@ export function createMethods({ runtime: R, getState, log = () => {} }) {
325
325
  const chatId = str(p.chatId);
326
326
  if (!chatId || !kind) throw bad('要给 chatId,kind 只能是 group / c2c');
327
327
  const text = str(p.content);
328
- if (!text && !p.msgId && !p.eventId) throw bad('content / msgId / eventId 至少给一个');
328
+ /**
329
+ * 富媒体(图文卡片 / markdown / 图片 / ark)**本来就不带正文**:
330
+ * `buildSendPayload()` 见到 card 会自己算 msg_type=8、并把 content 清空。
331
+ *
332
+ * 这里以前只认 text / msgId / eventId,于是「扩展直发一张官方卡片」
333
+ * 在协议层就被 400 挡掉:宿主 `narrowMsgSend` 明确不许扩展自报
334
+ * msgId / eventId(防伪造被动窗口),纯卡片永远凑不齐这三个条件,
335
+ * 表现出来就是面板上点「现在分享」毫无反应。
336
+ */
337
+ const hasRich = ['markdown', 'keyboard', 'media', 'card', 'ark']
338
+ .some((k) => p[k] !== undefined && p[k] !== null);
339
+ if (!text && !p.msgId && !p.eventId && !hasRich) {
340
+ throw bad('content / msgId / eventId / 富媒体至少给一个');
341
+ }
329
342
 
330
343
  const cid = str(p.clientMsgId).slice(0, 120);
331
344
  sweepSent();
@@ -808,6 +821,30 @@ export function createMethods({ runtime: R, getState, log = () => {} }) {
808
821
  registerMedia(def, { R, err, log });
809
822
  registerOps(def, { R, err, log });
810
823
 
824
+ /* ---------------- DSH 扩展反向互通(双向联动) ----------------
825
+ * 框架插件要调 DSH 侧已装扩展的能力时走这里:`ext.call` 推一条 SSE 事件
826
+ * 给 DSH,DSH 执行完用 RPC 回 `ext.call.reply`。桥接实例由 HostBridge 注入,
827
+ * 没接协议时整组方法不注册(面板能力表如实显示没有,不列一排 501)。
828
+ */
829
+ if (extBridge) {
830
+ def('ext.list', 'read', '列出 DSH 已装扩展暴露的动作', async () => extBridge.list());
831
+
832
+ def('ext.call', 'message', '调用 DSH 扩展的一个动作(经 SSE 请求 + RPC 回执)', async (p) => {
833
+ const out = await extBridge.call({
834
+ extId: str(p.extId), action: str(p.action), payload: p.payload ?? null, chat: str(p.chat ?? ''),
835
+ });
836
+ return { ok: true, result: out ?? null };
837
+ });
838
+
839
+ /** DSH 回执:由 DSH 用协议令牌主动调,scope 与 ext.call 一致 */
840
+ def('ext.call.reply', 'message', 'DSH 回传扩展调用结果(内部)', async (p) =>
841
+ extBridge.reply({ requestId: str(p.requestId), ok: p.ok !== false, result: p.result ?? null, error: str(p.error ?? '') }));
842
+
843
+ /** DSH 连上 / 扩展装卸后上报能力清单 */
844
+ def('ext.register', 'message', 'DSH 上报已装扩展能力清单(内部)', async (p) =>
845
+ extBridge.register({ extensions: p.extensions ?? [] }));
846
+ }
847
+
811
848
  /* ---------------- 插件工具 → 一等协议方法(方案 A) ---------------- */
812
849
 
813
850
  /**
package/src/outbound.js CHANGED
@@ -72,6 +72,16 @@ function briefOf(payload) {
72
72
  parts.push(`[markdown] ${String(b.markdown.content).replace(/\s+/g, ' ').trim()}`);
73
73
  }
74
74
  if (b.ark) parts.push('[ark 卡片]');
75
+ /**
76
+ * 官方图文卡片(msg_type=8)**没有正文**:content 必须为空,四个字段都在
77
+ * card 里。以前 briefOf 不认它,日志里就只剩「发出 …:(空)」,排查时
78
+ * 完全看不出刚才发的是哪张卡片。扁平 / 官方嵌套两种结构都认。
79
+ */
80
+ if (b.card) {
81
+ const c = b.card?.content ?? b.card;
82
+ const title = String(c?.title ?? '').trim();
83
+ parts.push(title ? `[图文卡片] ${title}` : '[图文卡片]');
84
+ }
75
85
  if (b.media) {
76
86
  // fileType 是数字(1 图 / 2 视频 / 3 语音 / 4 文件),直接打数字没人看得懂
77
87
  const name = { 1: '图片', 2: '视频', 3: '语音', 4: '文件' }[b.media.fileType ?? b.fileType];
@@ -252,7 +262,9 @@ export function digestTextOf(payload) {
252
262
  * 图文卡片(`msg_type=8`)带上标题。只写 `[卡片]` 的话,一天发十条卡片
253
263
  * 就是十条一模一样的记录,账本里根本分不出哪条是哪条。
254
264
  */
255
- const cardTitle = p.card?.content?.title;
265
+ /** 协议 / 扩展路径给的是扁平 `{title, …}`,`msg.replyTuwen()` 给的是嵌套 `{type,content}` */
266
+ const cardBody = p.card?.content ?? p.card;
267
+ const cardTitle = String(cardBody?.title ?? '').trim();
256
268
  if (p.card) return cardTitle ? `[图文卡片] ${cardTitle}` : '[图文卡片]';
257
269
  return '';
258
270
  }
@@ -407,7 +407,7 @@ export class PluginStorage {
407
407
  /**
408
408
  * 插件上下文:插件能用的全部能力都在这里,不暴露内部实现。
409
409
  */
410
- export function createContext({ meta, paths, registry, api, cfg, config, configStore, groups, roles, levels, outbound, session, pipeline, reach, ledger, gate, delivery, identity, isOwner, pages = null, routes = null, state = null }) {
410
+ export function createContext({ meta, paths, registry, api, cfg, config, configStore, groups, roles, levels, outbound, session, pipeline, reach, ledger, gate, delivery, identity, isOwner, pages = null, routes = null, state = null, extBridge = null }) {
411
411
  const id = meta.id;
412
412
  // 日志 tag 带机器人 id,多机器人下同名插件的日志不会串
413
413
  const logger = createLogger(`plugin:${paths?.id ?? '-'}:${id}`);
@@ -773,6 +773,28 @@ export function createContext({ meta, paths, registry, api, cfg, config, configS
773
773
  return callTool(name, args, opts);
774
774
  },
775
775
 
776
+ /**
777
+ * 调 DSH 侧已装扩展的能力(直连协议反向联动)。
778
+ *
779
+ * const list = await ctx.ext.list(); // 有哪些扩展 / 动作
780
+ * const r = await ctx.ext.call('bili', 'test_share', { bvid: 'BV…' });
781
+ *
782
+ * 没接外接协议时 `available` 为 false、`list()` 回空、`call()` 明确抛错,
783
+ * 不静默变成「什么都没发生」。扩展自己按 `ui.actions` 白名单把着动作,
784
+ * 框架插件不能凭空调一个没声明的函数。
785
+ */
786
+ ext: {
787
+ get available() { return Boolean(extBridge); },
788
+ async list() {
789
+ if (!extBridge) return { extensions: [], updatedAt: 0, pending: 0 };
790
+ return extBridge.list();
791
+ },
792
+ async call(extId, action, payload = null, opts = {}) {
793
+ if (!extBridge) throw new Error('没接 DSH 外接协议,调不了扩展能力');
794
+ return await extBridge.call({ extId, action, payload, chat: opts.chat ?? '' });
795
+ },
796
+ },
797
+
776
798
  /**
777
799
  * 定时任务。返回停止函数;插件卸载时会自动清理,不会残留。
778
800
  * ctx.schedule('daily-reset', 60_000, () => { ... })
@@ -30,7 +30,7 @@ const log = createLogger('plugins');
30
30
  * 启用状态存在 data/bots/<机器人id>/plugins.json,删掉文件夹即等于卸载。
31
31
  */
32
32
  export class PluginManager {
33
- constructor({ pluginsDir, paths, registry, api, cfg, goBin, groups, roles, outbound, session, pipeline, isOwner, reach, ledger, gate, delivery, identity, ignoreCompat }) {
33
+ constructor({ pluginsDir, paths, registry, api, cfg, goBin, groups, roles, outbound, session, pipeline, isOwner, reach, ledger, gate, delivery, identity, ignoreCompat, host = null }) {
34
34
  this.dir = pluginsDir;
35
35
  /** 插件声明的名字占用表(命令/工具/钩子),加载前查冲突、卸载时释放 */
36
36
  this.decl = new Declarations();
@@ -57,6 +57,8 @@ export class PluginManager {
57
57
  /** 身份对照表(只读给插件,见 context.js 的 readOnlyIdentity),见 src/identity.js */
58
58
  this.identity = identity;
59
59
  this.isOwner = isOwner;
60
+ /** 外接协议桥(可选,与 `loaded` 里那条 `host?` 不是一回事):透传给 ctx.ext */
61
+ this.hostBridge = host;
60
62
  /** 跳过插件声明的 frameworkVersion 校验(作者本地调试用) */
61
63
  this.ignoreCompat = Boolean(ignoreCompat);
62
64
  this.loaded = new Map(); // id -> { meta, ctx?, host?, dir, kind, menuMissing }
@@ -488,6 +490,7 @@ export class PluginManager {
488
490
  isOwner: this.isOwner,
489
491
  pages: this.pages,
490
492
  routes: this.routes,
493
+ extBridge: this.hostBridge?.extBridge ?? null,
491
494
  });
492
495
 
493
496
  await meta.setup(ctx);