@zhin.js/adapter-qq 5.0.3 → 6.0.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.
@@ -0,0 +1,147 @@
1
+ /**
2
+ * `qq endpoint` 命令的业务逻辑(与命令定义文件分离,便于测试)。
3
+ */
4
+ import { startQqBindFlow } from './qq-bind-flow.js';
5
+ import { persistQqCredentialsToEnv } from './qq-bind-persist.js';
6
+ import { addQqEndpointToConfig, listQqEndpointEntries, removeQqEndpointFromConfig, } from './qq-endpoint-config.js';
7
+ /**
8
+ * endpoint 管理命令的操作者校验:实例配置声明了 master(顶层或任一端点项)时
9
+ * 仅 master 可执行 add/cancel/remove;未配置则放行(首个扫码绑定者即为 owner,
10
+ * legacy applyBindOwnership 会把 operator 写为新端点的 master)。
11
+ */
12
+ export function isQqEndpointOperator(config, input) {
13
+ const cfg = (config ?? {});
14
+ const masters = new Set();
15
+ const collect = (value) => {
16
+ if (value === undefined || value === null)
17
+ return;
18
+ const text = String(value).trim();
19
+ if (text)
20
+ masters.add(text);
21
+ };
22
+ collect(cfg.master);
23
+ if (Array.isArray(cfg.endpoints)) {
24
+ for (const entry of cfg.endpoints) {
25
+ collect(entry?.master);
26
+ }
27
+ }
28
+ if (masters.size === 0)
29
+ return true;
30
+ const sender = String(input?.sender ?? '').trim();
31
+ return !!sender && masters.has(sender);
32
+ }
33
+ export const QQ_ENDPOINT_FORBIDDEN = '仅 master 可执行 QQ endpoint 管理命令';
34
+ /**
35
+ * 从命令 input(Runtime Message)提取 $reply;非消息来源(如 Host API 调用)降级为 no-op。
36
+ */
37
+ export function extractQqCommandReply(input) {
38
+ const reply = input?.$reply;
39
+ if (typeof reply === 'function') {
40
+ return (text) => reply.call(input, text);
41
+ }
42
+ return async () => undefined;
43
+ }
44
+ /** `qq endpoint list`:运行中的 endpoints(本 generation adapter create 注册)+ 配置里的 endpoints */
45
+ export function runQqEndpointList(state, projectRoot) {
46
+ const running = [...state.endpoints.values()];
47
+ const configured = listQqEndpointEntries(projectRoot);
48
+ const lines = [];
49
+ lines.push('【运行中的 QQ endpoints】');
50
+ if (running.length === 0) {
51
+ lines.push(' (无)');
52
+ }
53
+ else {
54
+ for (const endpoint of running) {
55
+ lines.push(` - ${endpoint.name}(${endpoint.mode})`);
56
+ }
57
+ }
58
+ lines.push('【配置中的 QQ endpoints】(zhin.config.yml → plugins.qq.endpoints)');
59
+ if (configured.length === 0) {
60
+ lines.push(' (无)');
61
+ }
62
+ else {
63
+ for (const entry of configured) {
64
+ lines.push(` - ${entry.name}(appid: ${entry.appid})`);
65
+ }
66
+ }
67
+ if (state.bindFlow) {
68
+ lines.push('⚠️ 有进行中的扫码绑定,可用 qq endpoint cancel 取消');
69
+ }
70
+ return lines.join('\n');
71
+ }
72
+ /**
73
+ * `qq endpoint add [name]`:启动扫码绑定流程。
74
+ * 返回的 Promise 在二维码链接就绪(或前置失败)时 resolve 为首条回复;
75
+ * 后续状态(已扫码 / 成功 / 失败 / 过期刷新)通过 reply 推回当前会话。
76
+ */
77
+ export function runQqEndpointAdd(state, name, reply, projectRoot) {
78
+ if (state.bindFlow) {
79
+ return Promise.resolve('已有进行中的 QQ 机器人绑定,请先发送 qq endpoint cancel 取消后再试');
80
+ }
81
+ const endpointName = name?.trim() || undefined;
82
+ return new Promise((resolve) => {
83
+ let firstReplied = false;
84
+ const settle = (text) => {
85
+ if (!firstReplied) {
86
+ firstReplied = true;
87
+ resolve(text);
88
+ return;
89
+ }
90
+ void reply(text);
91
+ };
92
+ const stop = startQqBindFlow({
93
+ onQrDisplayed: (url) => {
94
+ // QQ 出站当前仅支持纯文本(富媒体未迁移),二维码只能发链接文本
95
+ settle(`请用手机 QQ 打开以下链接完成扫码绑定(二维码图片出站暂未支持,故发送链接):\n${url}`);
96
+ },
97
+ onQrExpired: async () => {
98
+ await reply('二维码已过期,正在刷新,请扫描新链接…');
99
+ },
100
+ onSuccess: async (credentials) => {
101
+ state.bindFlow = null;
102
+ try {
103
+ const [{ appId, appSecret }] = credentials;
104
+ const finalName = endpointName ?? appId;
105
+ const envKeys = persistQqCredentialsToEnv(finalName, appId, appSecret, projectRoot);
106
+ const filePath = addQqEndpointToConfig({ name: finalName, appid: envKeys.appidRef, secret: envKeys.secretRef }, projectRoot);
107
+ settle(`✅ 绑定成功!endpoint「${finalName}」的凭据已写入 .env,并已追加到 ${filePath} 的 plugins.qq.endpoints。\n` +
108
+ '⚠️ 需重启 zhin 后新 endpoint 才会生效。');
109
+ }
110
+ catch (error) {
111
+ settle(`绑定成功但写入配置失败:${error instanceof Error ? error.message : String(error)}`);
112
+ }
113
+ },
114
+ onFailure: (error) => {
115
+ state.bindFlow = null;
116
+ settle(`❌ QQ 绑定失败:${error.message}`);
117
+ },
118
+ }, { source: 'zhin' });
119
+ state.bindFlow = { name: endpointName, stop };
120
+ });
121
+ }
122
+ /** `qq endpoint cancel`:中止进行中的绑定流程 */
123
+ export function runQqEndpointCancel(state) {
124
+ if (!state.bindFlow) {
125
+ return '当前没有进行中的 QQ 绑定流程';
126
+ }
127
+ state.bindFlow.stop();
128
+ state.bindFlow = null;
129
+ return '已取消进行中的 QQ 绑定流程';
130
+ }
131
+ /** `qq endpoint remove <name>`:从 zhin.config.yml 移除对应 endpoints 项 */
132
+ export function runQqEndpointRemove(_state, name, projectRoot) {
133
+ const trimmed = name.trim();
134
+ if (!trimmed)
135
+ return '用法:qq endpoint remove <name>';
136
+ try {
137
+ const { removed, filePath } = removeQqEndpointFromConfig(trimmed, projectRoot);
138
+ if (!removed) {
139
+ return `配置中不存在 qq endpoint「${trimmed}」(${filePath} → plugins.qq.endpoints)`;
140
+ }
141
+ return (`已从 ${filePath} 的 plugins.qq.endpoints 移除「${trimmed}」。\n` +
142
+ '⚠️ 需重启 zhin 后生效(运行中的连接届时才会断开);.env 中的凭据键未删除,可手动清理。');
143
+ }
144
+ catch (error) {
145
+ return `移除失败:${error instanceof Error ? error.message : String(error)}`;
146
+ }
147
+ }
@@ -0,0 +1,17 @@
1
+ export interface QqEndpointConfigEntry {
2
+ name: string;
3
+ appid: string;
4
+ secret: string;
5
+ [key: string]: unknown;
6
+ }
7
+ /** 定位项目配置文件:ZHIN_CONFIG 指定优先,否则发现 zhin.config.yml/.yaml,都没有则默认新建 zhin.config.yml */
8
+ export declare function findQqConfigFile(projectRoot?: string): string;
9
+ /** 读取 plugins.qq.endpoints(plain JS);plugins/qq 缺失或形态不符时返回 [] */
10
+ export declare function listQqEndpointEntries(projectRoot?: string): QqEndpointConfigEntry[];
11
+ /** 追加 endpoint 到 plugins.qq.endpoints;name 已存在时报错 */
12
+ export declare function addQqEndpointToConfig(entry: QqEndpointConfigEntry, projectRoot?: string): string;
13
+ /** 按 name 移除 plugins.qq.endpoints 项;不存在返回 false */
14
+ export declare function removeQqEndpointFromConfig(name: string, projectRoot?: string): {
15
+ removed: boolean;
16
+ filePath: string;
17
+ };
@@ -0,0 +1,110 @@
1
+ /**
2
+ * zhin.config.yml 中 plugins.qq.endpoints 的读写(Plugin Runtime 版)。
3
+ * 用 yaml Document 操作以保留现有注释;仅支持 .yml/.yaml,其它格式报错提示手动处理。
4
+ */
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { isMap, isSeq, parseDocument } from 'yaml';
8
+ import { resolveProjectRoot } from './qq-bind-persist.js';
9
+ const CONFIG_BASENAME = 'zhin.config';
10
+ const YAML_EXTENSIONS = ['.yml', '.yaml'];
11
+ /** 定位项目配置文件:ZHIN_CONFIG 指定优先,否则发现 zhin.config.yml/.yaml,都没有则默认新建 zhin.config.yml */
12
+ export function findQqConfigFile(projectRoot) {
13
+ const root = projectRoot ?? resolveProjectRoot();
14
+ const envConfig = process.env.ZHIN_CONFIG?.trim();
15
+ if (envConfig)
16
+ return path.resolve(root, envConfig);
17
+ for (const ext of YAML_EXTENSIONS) {
18
+ const candidate = path.join(root, `${CONFIG_BASENAME}${ext}`);
19
+ if (fs.existsSync(candidate))
20
+ return candidate;
21
+ }
22
+ for (const ext of ['.json', '.toml', '.ts']) {
23
+ const candidate = path.join(root, `${CONFIG_BASENAME}${ext}`);
24
+ if (fs.existsSync(candidate)) {
25
+ throw new Error(`暂不支持写入 ${ext} 配置文件,请手动在 ${CONFIG_BASENAME}${ext} 的 plugins.qq.endpoints 中维护`);
26
+ }
27
+ }
28
+ return path.join(root, `${CONFIG_BASENAME}.yml`);
29
+ }
30
+ function readConfigDocument(projectRoot) {
31
+ const filePath = findQqConfigFile(projectRoot);
32
+ const content = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf-8') : '';
33
+ const doc = parseDocument(content || '{}');
34
+ return { filePath, doc };
35
+ }
36
+ function writeConfigDocument({ filePath, doc }) {
37
+ fs.writeFileSync(filePath, doc.toString());
38
+ }
39
+ /** 读取 plugins.qq.endpoints(plain JS);plugins/qq 缺失或形态不符时返回 [] */
40
+ export function listQqEndpointEntries(projectRoot) {
41
+ const { doc } = readConfigDocument(projectRoot);
42
+ const plugins = doc.toJS()?.plugins;
43
+ if (!plugins || typeof plugins !== 'object' || Array.isArray(plugins))
44
+ return [];
45
+ const endpoints = plugins.qq?.endpoints;
46
+ if (!Array.isArray(endpoints))
47
+ return [];
48
+ return endpoints.filter((entry) => !!entry && typeof entry === 'object' && typeof entry.name === 'string');
49
+ }
50
+ function entryName(item) {
51
+ if (!isMap(item))
52
+ return undefined;
53
+ const name = item.get('name');
54
+ return typeof name === 'string' && name ? name : undefined;
55
+ }
56
+ /**
57
+ * 确保 plugins.qq.endpoints 存在并返回其 YAMLSeq(节点级操作,保留既有条目与注释)。
58
+ * `plugins: []`(legacy 空列表,Runtime 忽略)可直接替换为 map;非空数组拒绝写入。
59
+ */
60
+ function ensureEndpointsSeq(doc) {
61
+ const plugins = doc.get('plugins');
62
+ if (isSeq(plugins) && plugins.items.length > 0) {
63
+ throw new Error('配置的 plugins 是数组形态(legacy 插件名列表),请手动迁移为 map 后再试');
64
+ }
65
+ if (plugins !== undefined && !isMap(plugins) && !isSeq(plugins)) {
66
+ throw new Error('配置的 plugins 字段形态异常,请手动检查 zhin.config.yml');
67
+ }
68
+ if (!isMap(doc.get('plugins'))) {
69
+ // 注意:空对象 {} 不会被 doc.set 自动包装为 YAMLMap,必须显式 createNode
70
+ doc.set('plugins', doc.createNode({}));
71
+ }
72
+ const qq = doc.getIn(['plugins', 'qq']);
73
+ if (qq !== undefined && !isMap(qq)) {
74
+ throw new Error('配置的 plugins.qq 字段形态异常,请手动检查 zhin.config.yml');
75
+ }
76
+ if (!isMap(doc.getIn(['plugins', 'qq']))) {
77
+ doc.setIn(['plugins', 'qq'], doc.createNode({}));
78
+ }
79
+ const endpoints = doc.getIn(['plugins', 'qq', 'endpoints']);
80
+ if (endpoints !== undefined && !isSeq(endpoints)) {
81
+ throw new Error('配置的 plugins.qq.endpoints 字段形态异常,请手动检查 zhin.config.yml');
82
+ }
83
+ if (!isSeq(doc.getIn(['plugins', 'qq', 'endpoints']))) {
84
+ doc.setIn(['plugins', 'qq', 'endpoints'], doc.createNode([]));
85
+ }
86
+ return doc.getIn(['plugins', 'qq', 'endpoints']);
87
+ }
88
+ /** 追加 endpoint 到 plugins.qq.endpoints;name 已存在时报错 */
89
+ export function addQqEndpointToConfig(entry, projectRoot) {
90
+ const document = readConfigDocument(projectRoot);
91
+ const seq = ensureEndpointsSeq(document.doc);
92
+ if (seq.items.some((item) => entryName(item) === entry.name)) {
93
+ throw new Error(`配置中已存在 qq endpoint「${entry.name}」,可先 qq endpoint remove ${entry.name} 再重新添加`);
94
+ }
95
+ seq.items.push(document.doc.createNode(entry));
96
+ writeConfigDocument(document);
97
+ return document.filePath;
98
+ }
99
+ /** 按 name 移除 plugins.qq.endpoints 项;不存在返回 false */
100
+ export function removeQqEndpointFromConfig(name, projectRoot) {
101
+ const document = readConfigDocument(projectRoot);
102
+ const seq = ensureEndpointsSeq(document.doc);
103
+ const next = seq.items.filter((item) => entryName(item) !== name);
104
+ if (next.length === seq.items.length) {
105
+ return { removed: false, filePath: document.filePath };
106
+ }
107
+ seq.items = next;
108
+ writeConfigDocument(document);
109
+ return { removed: true, filePath: document.filePath };
110
+ }
@@ -0,0 +1,17 @@
1
+ export interface QqRunningEndpoint {
2
+ name: string;
3
+ mode: string;
4
+ }
5
+ export interface QqBindFlowHandle {
6
+ /** 绑定期望的 endpoint 名(未指定时为 undefined,成功后取 appId) */
7
+ name?: string;
8
+ stop: () => void;
9
+ }
10
+ export interface QqRuntimeState {
11
+ /** 当前 generation 已成功创建的 endpoint(name → 描述) */
12
+ readonly endpoints: Map<string, QqRunningEndpoint>;
13
+ /** 全局单例:同一时间只允许一个扫码绑定流程 */
14
+ bindFlow: QqBindFlowHandle | null;
15
+ }
16
+ export declare function createQqRuntimeState(): QqRuntimeState;
17
+ export declare const qqRuntimeStateToken: import("@zhin.js/plugin-runtime").Token<QqRuntimeState>;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * QQ 插件实例的运行时状态:adapter create() 注册的 endpoint 列表 +
3
+ * 扫码绑定流程的全局单例。由 plugin.ts setup() provide,
4
+ * adapter create 与 commands 通过 use(qqRuntimeStateToken) 共享(同一 owner generation)。
5
+ */
6
+ import { createToken } from '@zhin.js/plugin-runtime';
7
+ export function createQqRuntimeState() {
8
+ return {
9
+ endpoints: new Map(),
10
+ bindFlow: null,
11
+ };
12
+ }
13
+ export const qqRuntimeStateToken = createToken('zhin.qq.runtime-state', 'QQ adapter runtime state (running endpoints + bind flow singleton)');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhin.js/adapter-qq",
3
- "version": "5.0.3",
3
+ "version": "6.0.0",
4
4
  "description": "Zhin.js QQ Official adapter for Plugin Runtime (WebSocket gateway)",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -35,19 +35,21 @@
35
35
  },
36
36
  "dependencies": {
37
37
  "qq-official-bot": "^1.2.3",
38
- "@zhin.js/adapter": "1.0.1",
39
- "@zhin.js/core": "1.3.5",
40
- "@zhin.js/host-http": "1.0.1",
38
+ "yaml": "^2.9.0",
39
+ "@zhin.js/adapter": "1.1.0",
40
+ "@zhin.js/core": "1.4.0",
41
+ "@zhin.js/host-http": "1.0.2",
41
42
  "@zhin.js/logger": "1.0.75",
42
- "@zhin.js/plugin-runtime": "1.0.1"
43
+ "@zhin.js/plugin-runtime": "1.1.0",
44
+ "@zhin.js/command": "1.0.2"
43
45
  },
44
46
  "peerDependencies": {
45
47
  "zod": "^4.0.0",
46
- "@zhin.js/adapter": "1.0.1",
47
- "@zhin.js/agent": "1.0.4",
48
- "@zhin.js/core": "1.3.5",
49
- "@zhin.js/plugin-runtime": "1.0.1",
50
- "zhin.js": "4.1.3"
48
+ "@zhin.js/adapter": "1.1.0",
49
+ "@zhin.js/agent": "1.0.5",
50
+ "@zhin.js/core": "1.4.0",
51
+ "@zhin.js/plugin-runtime": "1.1.0",
52
+ "zhin.js": "5.0.0"
51
53
  },
52
54
  "peerDependenciesMeta": {
53
55
  "zhin.js": {
@@ -65,12 +67,13 @@
65
67
  "typescript": "^6.0.3",
66
68
  "vitest": "^4.1.10",
67
69
  "zod": "^4.4.3",
68
- "@zhin.js/agent": "1.0.4",
69
- "@zhin.js/host-http": "1.0.1",
70
- "zhin.js": "4.1.3"
70
+ "@zhin.js/agent": "1.0.5",
71
+ "@zhin.js/host-http": "1.0.2",
72
+ "zhin.js": "5.0.0"
71
73
  },
72
74
  "files": [
73
75
  "adapters",
76
+ "commands",
74
77
  "plugin.ts",
75
78
  "schema.json",
76
79
  "src",
@@ -96,6 +99,10 @@
96
99
  {
97
100
  "package": "@zhin.js/adapter",
98
101
  "api": "^1.0.0"
102
+ },
103
+ {
104
+ "package": "@zhin.js/command",
105
+ "api": "^1.0.0"
99
106
  }
100
107
  ],
101
108
  "plugins": []
package/plugin.ts CHANGED
@@ -1,12 +1,15 @@
1
1
  import { definePlugin } from '@zhin.js/plugin-runtime';
2
2
  import { registerQqPlatformPermitChecker } from './src/platform-permit.js';
3
+ import { createQqRuntimeState, qqRuntimeStateToken } from './src/qq-runtime-state.js';
3
4
 
4
5
  export default definePlugin({
5
6
  name: 'qq',
6
7
  metadata: {
7
8
  displayName: 'QQ Official WebSocket Adapter',
8
9
  },
9
- setup() {
10
+ setup(context) {
11
+ // 运行中 endpoint 注册表 + 扫码绑定单例,供 adapter create 与 `qq endpoint` 命令共享
12
+ context.resources.provide(qqRuntimeStateToken, createQqRuntimeState());
10
13
  // 平台权限门禁:guild_owner / guild_admin / manage_roles / manage_channels(agent 工具 platformPermit)
11
14
  return registerQqPlatformPermitChecker();
12
15
  },
package/schema.json CHANGED
@@ -3,19 +3,13 @@
3
3
  "type": "object",
4
4
  "additionalProperties": false,
5
5
  "properties": {
6
- "name": {
7
- "type": "string",
8
- "default": "qq-bot"
9
- },
10
- "appid": {
11
- "type": "string"
12
- },
13
- "secret": {
14
- "type": "string"
15
- },
16
6
  "mode": {
17
7
  "type": "string",
18
- "enum": ["websocket", "webhook", "middleware"],
8
+ "enum": [
9
+ "websocket",
10
+ "webhook",
11
+ "middleware"
12
+ ],
19
13
  "default": "websocket",
20
14
  "description": "WebSocket gateway (default). webhook/middleware use httpHostToken POST."
21
15
  },
@@ -23,9 +17,15 @@
23
17
  "type": "boolean",
24
18
  "default": false
25
19
  },
20
+ "master": {
21
+ "type": ["string", "number"],
22
+ "description": "Endpoint Owner(qq endpoint 管理命令权限、AI master 角色);endpoints[i] 可逐项覆盖"
23
+ },
26
24
  "intents": {
27
25
  "type": "array",
28
- "items": { "type": "string" }
26
+ "items": {
27
+ "type": "string"
28
+ }
29
29
  },
30
30
  "accessTokenUrl": {
31
31
  "type": "string"
@@ -45,7 +45,41 @@
45
45
  "path": {
46
46
  "type": "string",
47
47
  "description": "Legacy standalone webhook path (unused with httpHostToken)."
48
+ },
49
+ "endpoints": {
50
+ "type": "array",
51
+ "description": "多账号:一个插件实例挂多个 endpoint。每项与顶层字段同构(name 必填,其余覆盖顶层)",
52
+ "items": {
53
+ "type": "object",
54
+ "additionalProperties": true,
55
+ "properties": {
56
+ "name": {
57
+ "type": "string",
58
+ "description": "QQ bot name"
59
+ },
60
+ "appid": {
61
+ "type": "string",
62
+ "description": "QQ official bot app ID"
63
+ },
64
+ "secret": {
65
+ "type": "string",
66
+ "description": "QQ official bot secret"
67
+ }
68
+ },
69
+ "required": [
70
+ "name",
71
+ "appid",
72
+ "secret"
73
+ ]
74
+ }
75
+ },
76
+ "commandPrefix": {
77
+ "type": "string",
78
+ "default": "",
79
+ "description": "命令前缀(默认 '' 无前缀,任意文本按命令匹配;如 '/' 要求 / 开头)。endpoints[i] 可逐项覆盖"
48
80
  }
49
81
  },
50
- "required": ["appid", "secret"]
82
+ "required": [
83
+ "endpoints"
84
+ ]
51
85
  }
package/src/endpoint.ts CHANGED
@@ -1,7 +1,11 @@
1
1
  /**
2
2
  * QQ endpoints — lifecycle, outbound, admit, agent tool surface.
3
3
  */
4
- import type { EndpointInstance } from '@zhin.js/adapter';
4
+ import type {
5
+ EndpointChannel,
6
+ EndpointInstance,
7
+ EndpointManagement,
8
+ } from '@zhin.js/adapter';
5
9
  import type { MessageGateway } from '@zhin.js/core/runtime';
6
10
  import type { HttpHost } from '@zhin.js/host-http';
7
11
  import { formatCompact, getLogger } from '@zhin.js/logger';
@@ -51,12 +55,18 @@ export class QqWebsocketEndpoint implements EndpointInstance {
51
55
  #open = false;
52
56
  #started = false;
53
57
  #unregisterAgent?: () => void;
58
+ readonly management: EndpointManagement = createQqEndpointManagement(this);
54
59
 
55
60
  constructor(options: QqEndpointOptions) {
56
61
  this.#options = options;
57
62
  this.#createBot = options.createBot ?? defaultCreateBot;
58
63
  }
59
64
 
65
+ /** Live endpoint 名(Console/AdapterIndex 展示用,如 bot appid 别名)。 */
66
+ get name(): string {
67
+ return this.#options.config.name;
68
+ }
69
+
60
70
  async start(): Promise<void> {
61
71
  if (this.#started) return;
62
72
  this.#started = true;
@@ -227,12 +237,18 @@ export class QqHttpEndpoint implements EndpointInstance {
227
237
  #open = false;
228
238
  #started = false;
229
239
  #unregisterAgent?: () => void;
240
+ readonly management: EndpointManagement = createQqEndpointManagement(this);
230
241
 
231
242
  constructor(options: QqHttpEndpointOptions) {
232
243
  this.#options = options;
233
244
  this.#createBot = options.createBot ?? defaultCreateHttpBot;
234
245
  }
235
246
 
247
+ /** Live endpoint 名(Console/AdapterIndex 展示用)。 */
248
+ get name(): string {
249
+ return this.#options.config.name;
250
+ }
251
+
236
252
  async start(): Promise<void> {
237
253
  if (this.#started) return;
238
254
  this.#started = true;
@@ -387,3 +403,39 @@ export class QqHttpEndpoint implements EndpointInstance {
387
403
  return this.#bot;
388
404
  }
389
405
  }
406
+
407
+ function createQqEndpointManagement(endpoint: {
408
+ getGuilds(): Promise<unknown[]>;
409
+ getChannels(guildId: string): Promise<unknown[]>;
410
+ }): EndpointManagement {
411
+ return Object.freeze<EndpointManagement>({
412
+ async listChannels(): Promise<readonly EndpointChannel[]> {
413
+ const channels: EndpointChannel[] = [];
414
+ const guilds = await endpoint.getGuilds();
415
+ for (const guildValue of Array.isArray(guilds) ? guilds : []) {
416
+ const guild = asRecord(guildValue);
417
+ const guildId = String(guild.id ?? guild.guild_id ?? guildValue ?? '');
418
+ if (!guildId) continue;
419
+ const guildName = String(guild.name ?? guild.guild_name ?? guildId);
420
+ const rows = await endpoint.getChannels(guildId);
421
+ for (const channelValue of Array.isArray(rows) ? rows : []) {
422
+ const channel = asRecord(channelValue);
423
+ const id = String(channel.id ?? channel.channel_id ?? channelValue ?? '');
424
+ if (!id) continue;
425
+ channels.push({
426
+ id,
427
+ name: String(channel.name ?? channel.channel_name ?? id),
428
+ parent: { type: 'guild', id: guildId, name: guildName },
429
+ });
430
+ }
431
+ }
432
+ return channels;
433
+ },
434
+ });
435
+ }
436
+
437
+ function asRecord(value: unknown): Record<string, unknown> {
438
+ return value !== null && typeof value === 'object'
439
+ ? value as Record<string, unknown>
440
+ : {};
441
+ }