@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,145 @@
1
+ /**
2
+ * QQ Bot 扫码绑定协议(内联)
3
+ * Protocol aligned with @tencent-connect/qqbot-connector@1.1.0 qqbot-session — inlined to avoid runtime dependency.
4
+ */
5
+ import { createDecipheriv, randomBytes } from 'node:crypto';
6
+
7
+ export type QQBotEnv = 'production' | 'test';
8
+
9
+ const HOSTS: Record<QQBotEnv, string> = {
10
+ production: 'q.qq.com',
11
+ test: 'test.q.qq.com',
12
+ };
13
+
14
+ export enum BindStatus {
15
+ NONE = 0,
16
+ PENDING = 1,
17
+ COMPLETED = 2,
18
+ EXPIRED = 3,
19
+ }
20
+
21
+ export function getQQBotHost(env: QQBotEnv = 'production'): string {
22
+ return HOSTS[env];
23
+ }
24
+
25
+ export function generateBindKey(): string {
26
+ return randomBytes(32).toString('base64');
27
+ }
28
+
29
+ export function buildConnectUrl(taskId: string, source = 'zhin'): string {
30
+ return `https://${getQQBotHost('production')}/qqbot/openclaw/connect.html?task_id=${encodeURIComponent(taskId)}&source=${encodeURIComponent(source)}&_wv=2`;
31
+ }
32
+
33
+ /**
34
+ * AES-256-GCM 解密 base64 密文。
35
+ * 密文格式: IV(12 bytes) + ciphertext + AuthTag(16 bytes)
36
+ */
37
+ export function decryptSecret(encryptedBase64: string, keyBase64: string): string {
38
+ const key = Buffer.from(keyBase64, 'base64');
39
+ const payload = Buffer.from(encryptedBase64, 'base64');
40
+ const iv = payload.subarray(0, 12);
41
+ const authTag = payload.subarray(payload.length - 16);
42
+ const ciphertext = payload.subarray(12, payload.length - 16);
43
+ const decipher = createDecipheriv('aes-256-gcm', key, iv);
44
+ decipher.setAuthTag(authTag);
45
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
46
+ }
47
+
48
+ interface LiteApiResponse<T> {
49
+ retcode: number;
50
+ msg?: string;
51
+ data?: T;
52
+ }
53
+
54
+ async function postJson<T>(
55
+ url: string,
56
+ body: Record<string, unknown>,
57
+ timeoutMs: number,
58
+ ): Promise<LiteApiResponse<T>> {
59
+ const controller = new AbortController();
60
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
61
+ try {
62
+ const res = await fetch(url, {
63
+ method: 'POST',
64
+ headers: {
65
+ 'Content-Type': 'application/json',
66
+ Accept: 'application/json',
67
+ },
68
+ body: JSON.stringify(body),
69
+ signal: controller.signal,
70
+ });
71
+ if (!res.ok) {
72
+ throw new Error(`HTTP ${res.status} from ${url}`);
73
+ }
74
+ return (await res.json()) as LiteApiResponse<T>;
75
+ } finally {
76
+ clearTimeout(timer);
77
+ }
78
+ }
79
+
80
+ export interface BindTaskResult {
81
+ taskId: string;
82
+ key: string;
83
+ }
84
+
85
+ export async function createBindTask(
86
+ env: QQBotEnv = 'production',
87
+ timeoutMs = 10_000,
88
+ ): Promise<BindTaskResult> {
89
+ const url = `https://${getQQBotHost(env)}/lite/create_bind_task`;
90
+ const key = generateBindKey();
91
+ const res = await postJson<{ task_id?: string }>(url, { key }, timeoutMs);
92
+ if (res.retcode !== 0) {
93
+ throw new Error(res.msg ?? 'create_bind_task failed');
94
+ }
95
+ if (!res.data?.task_id) {
96
+ throw new Error('create_bind_task: missing task_id');
97
+ }
98
+ return { taskId: res.data.task_id, key };
99
+ }
100
+
101
+ export interface PollBindResultOk {
102
+ status: BindStatus;
103
+ botAppId: string;
104
+ botEncryptSecret: string;
105
+ /** 扫码绑定开发者 QQ 的 OpenID(poll_bind_result 返回) */
106
+ userOpenId: string;
107
+ }
108
+
109
+ export function parsePollBindResultData(data: {
110
+ status?: number;
111
+ bot_appid?: string | number;
112
+ bot_encrypt_secret?: string;
113
+ user_openid?: string;
114
+ userOpenid?: string;
115
+ openid?: string;
116
+ } | undefined): PollBindResultOk {
117
+ return {
118
+ status: (data?.status ?? BindStatus.NONE) as BindStatus,
119
+ botAppId: String(data?.bot_appid ?? ''),
120
+ botEncryptSecret: data?.bot_encrypt_secret ?? '',
121
+ userOpenId: String(
122
+ data?.user_openid ?? data?.userOpenid ?? data?.openid ?? '',
123
+ ),
124
+ };
125
+ }
126
+
127
+ export async function pollBindResult(
128
+ taskId: string,
129
+ env: QQBotEnv = 'production',
130
+ timeoutMs = 10_000,
131
+ ): Promise<PollBindResultOk> {
132
+ const url = `https://${getQQBotHost(env)}/lite/poll_bind_result`;
133
+ const res = await postJson<{
134
+ status?: number;
135
+ bot_appid?: string | number;
136
+ bot_encrypt_secret?: string;
137
+ user_openid?: string;
138
+ userOpenid?: string;
139
+ openid?: string;
140
+ }>(url, { task_id: taskId }, timeoutMs);
141
+ if (res.retcode !== 0) {
142
+ throw new Error(res.msg ?? 'poll_bind_result failed');
143
+ }
144
+ return parsePollBindResultData(res.data);
145
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * QQ Bot 扫码绑定流程(内联,等价 qqbot-connector startQrConnect)
3
+ */
4
+ import {
5
+ BindStatus,
6
+ buildConnectUrl,
7
+ createBindTask,
8
+ decryptSecret,
9
+ pollBindResult,
10
+ } from './qq-bind-api.js';
11
+
12
+ const POLL_INTERVAL_MS = 2000;
13
+
14
+ export interface QqBindCredentials {
15
+ appId: string;
16
+ appSecret: string;
17
+ userOpenId?: string;
18
+ }
19
+
20
+ export interface QqBindCallbacks {
21
+ onSuccess: (credentials: QqBindCredentials[]) => void;
22
+ onFailure: (error: Error) => void;
23
+ onQrDisplayed?: (url: string) => void | Promise<void>;
24
+ onQrExpired?: () => void | Promise<void>;
25
+ }
26
+
27
+ export interface QqBindFlowOptions {
28
+ signal?: AbortSignal;
29
+ source?: string;
30
+ }
31
+
32
+ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
33
+ return new Promise((resolve, reject) => {
34
+ if (signal?.aborted) {
35
+ reject(new DOMException('Aborted', 'AbortError'));
36
+ return;
37
+ }
38
+ const timer = setTimeout(resolve, ms);
39
+ signal?.addEventListener(
40
+ 'abort',
41
+ () => {
42
+ clearTimeout(timer);
43
+ reject(new DOMException('Aborted', 'AbortError'));
44
+ },
45
+ { once: true },
46
+ );
47
+ });
48
+ }
49
+
50
+ async function pollUntilResult(
51
+ taskId: string,
52
+ key: string,
53
+ signal?: AbortSignal,
54
+ ): Promise<{ outcome: 'scanned'; appId: string; appSecret: string; userOpenId: string } | { outcome: 'expired' }> {
55
+ while (!signal?.aborted) {
56
+ let result;
57
+ try {
58
+ result = await pollBindResult(taskId);
59
+ } catch {
60
+ await sleep(POLL_INTERVAL_MS, signal);
61
+ continue;
62
+ }
63
+ if (result.status === BindStatus.COMPLETED) {
64
+ const appSecret = decryptSecret(result.botEncryptSecret, key);
65
+ return {
66
+ outcome: 'scanned',
67
+ appId: result.botAppId,
68
+ appSecret,
69
+ userOpenId: result.userOpenId,
70
+ };
71
+ }
72
+ if (result.status === BindStatus.EXPIRED) {
73
+ return { outcome: 'expired' };
74
+ }
75
+ await sleep(POLL_INTERVAL_MS, signal);
76
+ }
77
+ throw new DOMException('Aborted', 'AbortError');
78
+ }
79
+
80
+ /**
81
+ * 轮询等待扫码结果(回调风格)。返回 stop 函数可中止流程。
82
+ */
83
+ export function startQqBindFlow(
84
+ callbacks: QqBindCallbacks,
85
+ options: QqBindFlowOptions = {},
86
+ ): () => void {
87
+ const controller = new AbortController();
88
+ const signal = options.signal
89
+ ? AbortSignal.any([controller.signal, options.signal])
90
+ : controller.signal;
91
+
92
+ void (async () => {
93
+ for (;;) {
94
+ if (signal.aborted) {
95
+ throw new DOMException('Aborted', 'AbortError');
96
+ }
97
+ let task;
98
+ try {
99
+ task = await createBindTask();
100
+ } catch (err) {
101
+ throw new Error(
102
+ `获取绑定任务失败: ${err instanceof Error ? err.message : String(err)}`,
103
+ { cause: err },
104
+ );
105
+ }
106
+ const connectUrl = buildConnectUrl(task.taskId, options.source ?? 'zhin');
107
+ await callbacks.onQrDisplayed?.(connectUrl);
108
+ const pollResult = await pollUntilResult(task.taskId, task.key, signal);
109
+ if (pollResult.outcome === 'scanned') {
110
+ callbacks.onSuccess([{
111
+ appId: pollResult.appId,
112
+ appSecret: pollResult.appSecret,
113
+ userOpenId: pollResult.userOpenId || undefined,
114
+ }]);
115
+ return;
116
+ }
117
+ await callbacks.onQrExpired?.();
118
+ }
119
+ })().catch((err) => {
120
+ if (err instanceof DOMException && err.name === 'AbortError') {
121
+ return;
122
+ }
123
+ callbacks.onFailure(err instanceof Error ? err : new Error(String(err)));
124
+ });
125
+
126
+ return () => controller.abort();
127
+ }
@@ -0,0 +1,71 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ export interface QqCredentialEnvKeys {
5
+ appidKey: string;
6
+ secretKey: string;
7
+ appidRef: string;
8
+ secretRef: string;
9
+ }
10
+
11
+ /** 按 endpoint 名称生成唯一 env 键(如 `QQ_MY_BOT_APPID`) */
12
+ export function buildQqCredentialEnvKeys(endpointName: string): QqCredentialEnvKeys {
13
+ const slug = endpointName.replace(/[^a-zA-Z0-9_]/g, '_').toUpperCase();
14
+ const appidKey = `QQ_${slug}_APPID`;
15
+ const secretKey = `QQ_${slug}_SECRET`;
16
+ return {
17
+ appidKey,
18
+ secretKey,
19
+ appidRef: `\${${appidKey}}`,
20
+ secretRef: `\${${secretKey}}`,
21
+ };
22
+ }
23
+
24
+ /** 项目根:ZHIN_PROJECT_ROOT 优先,缺省 process.cwd()(替代 legacy runtimeCwd) */
25
+ export function resolveProjectRoot(): string {
26
+ const envRoot = process.env.ZHIN_PROJECT_ROOT?.trim();
27
+ return path.resolve(envRoot || process.cwd());
28
+ }
29
+
30
+ function escapeRegExp(text: string): string {
31
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
32
+ }
33
+
34
+ function upsertEnvLine(content: string, key: string, value: string): string {
35
+ const lineRe = new RegExp(`^${escapeRegExp(key)}\\s*=.*$`, 'm');
36
+ const newLine = `${key}=${value}`;
37
+ if (lineRe.test(content)) {
38
+ return content.replace(lineRe, newLine);
39
+ }
40
+ const trimmed = content.replace(/\s*$/, '');
41
+ if (trimmed.length === 0) {
42
+ return `${newLine}\n`;
43
+ }
44
+ return `${trimmed}\n${newLine}\n`;
45
+ }
46
+
47
+ /** 写入或更新 `.env` 中的键值,并同步到当前进程 `process.env` */
48
+ export function persistQqCredentialsToEnv(
49
+ endpointName: string,
50
+ appId: string,
51
+ appSecret: string,
52
+ projectRoot?: string,
53
+ ): QqCredentialEnvKeys {
54
+ const keys = buildQqCredentialEnvKeys(endpointName);
55
+ const root = projectRoot ?? resolveProjectRoot();
56
+ const envPath = path.join(root, '.env');
57
+ let content = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf-8') : '';
58
+
59
+ const entries: Record<string, string> = {
60
+ [keys.appidKey]: appId,
61
+ [keys.secretKey]: appSecret,
62
+ };
63
+
64
+ for (const [key, value] of Object.entries(entries)) {
65
+ content = upsertEnvLine(content, key, value);
66
+ process.env[key] = value;
67
+ }
68
+
69
+ fs.writeFileSync(envPath, content);
70
+ return keys;
71
+ }
@@ -0,0 +1,174 @@
1
+ /**
2
+ * `qq endpoint` 命令的业务逻辑(与命令定义文件分离,便于测试)。
3
+ */
4
+ import { startQqBindFlow } from './qq-bind-flow.js';
5
+ import { persistQqCredentialsToEnv } from './qq-bind-persist.js';
6
+ import {
7
+ addQqEndpointToConfig,
8
+ listQqEndpointEntries,
9
+ removeQqEndpointFromConfig,
10
+ } from './qq-endpoint-config.js';
11
+ import type { QqRuntimeState } from './qq-runtime-state.js';
12
+
13
+ export type QqCommandReply = (text: string) => Promise<unknown>;
14
+
15
+ /**
16
+ * endpoint 管理命令的操作者校验:实例配置声明了 master(顶层或任一端点项)时
17
+ * 仅 master 可执行 add/cancel/remove;未配置则放行(首个扫码绑定者即为 owner,
18
+ * legacy applyBindOwnership 会把 operator 写为新端点的 master)。
19
+ */
20
+ export function isQqEndpointOperator(config: unknown, input: unknown): boolean {
21
+ const cfg = (config ?? {}) as { master?: unknown; endpoints?: unknown };
22
+ const masters = new Set<string>();
23
+ const collect = (value: unknown) => {
24
+ if (value === undefined || value === null) return;
25
+ const text = String(value).trim();
26
+ if (text) masters.add(text);
27
+ };
28
+ collect(cfg.master);
29
+ if (Array.isArray(cfg.endpoints)) {
30
+ for (const entry of cfg.endpoints) {
31
+ collect((entry as { master?: unknown } | null | undefined)?.master);
32
+ }
33
+ }
34
+ if (masters.size === 0) return true;
35
+ const sender = String((input as { sender?: unknown } | null | undefined)?.sender ?? '').trim();
36
+ return !!sender && masters.has(sender);
37
+ }
38
+
39
+ export const QQ_ENDPOINT_FORBIDDEN = '仅 master 可执行 QQ endpoint 管理命令';
40
+
41
+ /**
42
+ * 从命令 input(Runtime Message)提取 $reply;非消息来源(如 Host API 调用)降级为 no-op。
43
+ */
44
+ export function extractQqCommandReply(input: unknown): QqCommandReply {
45
+ const reply = (input as { $reply?: unknown } | null | undefined)?.$reply;
46
+ if (typeof reply === 'function') {
47
+ return (text) => (reply as (content: string) => Promise<unknown>).call(input, text);
48
+ }
49
+ return async () => undefined;
50
+ }
51
+
52
+ /** `qq endpoint list`:运行中的 endpoints(本 generation adapter create 注册)+ 配置里的 endpoints */
53
+ export function runQqEndpointList(state: QqRuntimeState, projectRoot?: string): string {
54
+ const running = [...state.endpoints.values()];
55
+ const configured = listQqEndpointEntries(projectRoot);
56
+ const lines: string[] = [];
57
+ lines.push('【运行中的 QQ endpoints】');
58
+ if (running.length === 0) {
59
+ lines.push(' (无)');
60
+ } else {
61
+ for (const endpoint of running) {
62
+ lines.push(` - ${endpoint.name}(${endpoint.mode})`);
63
+ }
64
+ }
65
+ lines.push('【配置中的 QQ endpoints】(zhin.config.yml → plugins.qq.endpoints)');
66
+ if (configured.length === 0) {
67
+ lines.push(' (无)');
68
+ } else {
69
+ for (const entry of configured) {
70
+ lines.push(` - ${entry.name}(appid: ${entry.appid})`);
71
+ }
72
+ }
73
+ if (state.bindFlow) {
74
+ lines.push('⚠️ 有进行中的扫码绑定,可用 qq endpoint cancel 取消');
75
+ }
76
+ return lines.join('\n');
77
+ }
78
+
79
+ /**
80
+ * `qq endpoint add [name]`:启动扫码绑定流程。
81
+ * 返回的 Promise 在二维码链接就绪(或前置失败)时 resolve 为首条回复;
82
+ * 后续状态(已扫码 / 成功 / 失败 / 过期刷新)通过 reply 推回当前会话。
83
+ */
84
+ export function runQqEndpointAdd(
85
+ state: QqRuntimeState,
86
+ name: string | undefined,
87
+ reply: QqCommandReply,
88
+ projectRoot?: string,
89
+ ): Promise<string> {
90
+ if (state.bindFlow) {
91
+ return Promise.resolve('已有进行中的 QQ 机器人绑定,请先发送 qq endpoint cancel 取消后再试');
92
+ }
93
+ const endpointName = name?.trim() || undefined;
94
+ return new Promise<string>((resolve) => {
95
+ let firstReplied = false;
96
+ const settle = (text: string) => {
97
+ if (!firstReplied) {
98
+ firstReplied = true;
99
+ resolve(text);
100
+ return;
101
+ }
102
+ void reply(text);
103
+ };
104
+ const stop = startQqBindFlow(
105
+ {
106
+ onQrDisplayed: (url) => {
107
+ // QQ 出站当前仅支持纯文本(富媒体未迁移),二维码只能发链接文本
108
+ settle(
109
+ `请用手机 QQ 打开以下链接完成扫码绑定(二维码图片出站暂未支持,故发送链接):\n${url}`,
110
+ );
111
+ },
112
+ onQrExpired: async () => {
113
+ await reply('二维码已过期,正在刷新,请扫描新链接…');
114
+ },
115
+ onSuccess: async (credentials) => {
116
+ state.bindFlow = null;
117
+ try {
118
+ const [{ appId, appSecret }] = credentials;
119
+ const finalName = endpointName ?? appId;
120
+ const envKeys = persistQqCredentialsToEnv(finalName, appId, appSecret, projectRoot);
121
+ const filePath = addQqEndpointToConfig(
122
+ { name: finalName, appid: envKeys.appidRef, secret: envKeys.secretRef },
123
+ projectRoot,
124
+ );
125
+ settle(
126
+ `✅ 绑定成功!endpoint「${finalName}」的凭据已写入 .env,并已追加到 ${filePath} 的 plugins.qq.endpoints。\n` +
127
+ '⚠️ 需重启 zhin 后新 endpoint 才会生效。',
128
+ );
129
+ } catch (error) {
130
+ settle(`绑定成功但写入配置失败:${error instanceof Error ? error.message : String(error)}`);
131
+ }
132
+ },
133
+ onFailure: (error) => {
134
+ state.bindFlow = null;
135
+ settle(`❌ QQ 绑定失败:${error.message}`);
136
+ },
137
+ },
138
+ { source: 'zhin' },
139
+ );
140
+ state.bindFlow = { name: endpointName, stop };
141
+ });
142
+ }
143
+
144
+ /** `qq endpoint cancel`:中止进行中的绑定流程 */
145
+ export function runQqEndpointCancel(state: QqRuntimeState): string {
146
+ if (!state.bindFlow) {
147
+ return '当前没有进行中的 QQ 绑定流程';
148
+ }
149
+ state.bindFlow.stop();
150
+ state.bindFlow = null;
151
+ return '已取消进行中的 QQ 绑定流程';
152
+ }
153
+
154
+ /** `qq endpoint remove <name>`:从 zhin.config.yml 移除对应 endpoints 项 */
155
+ export function runQqEndpointRemove(
156
+ _state: QqRuntimeState,
157
+ name: string,
158
+ projectRoot?: string,
159
+ ): string {
160
+ const trimmed = name.trim();
161
+ if (!trimmed) return '用法:qq endpoint remove <name>';
162
+ try {
163
+ const { removed, filePath } = removeQqEndpointFromConfig(trimmed, projectRoot);
164
+ if (!removed) {
165
+ return `配置中不存在 qq endpoint「${trimmed}」(${filePath} → plugins.qq.endpoints)`;
166
+ }
167
+ return (
168
+ `已从 ${filePath} 的 plugins.qq.endpoints 移除「${trimmed}」。\n` +
169
+ '⚠️ 需重启 zhin 后生效(运行中的连接届时才会断开);.env 中的凭据键未删除,可手动清理。'
170
+ );
171
+ } catch (error) {
172
+ return `移除失败:${error instanceof Error ? error.message : String(error)}`;
173
+ }
174
+ }
@@ -0,0 +1,135 @@
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, type YAMLSeq } from 'yaml';
8
+ import { resolveProjectRoot } from './qq-bind-persist.js';
9
+
10
+ export interface QqEndpointConfigEntry {
11
+ name: string;
12
+ appid: string;
13
+ secret: string;
14
+ [key: string]: unknown;
15
+ }
16
+
17
+ const CONFIG_BASENAME = 'zhin.config';
18
+ const YAML_EXTENSIONS = ['.yml', '.yaml'] as const;
19
+
20
+ /** 定位项目配置文件:ZHIN_CONFIG 指定优先,否则发现 zhin.config.yml/.yaml,都没有则默认新建 zhin.config.yml */
21
+ export function findQqConfigFile(projectRoot?: string): string {
22
+ const root = projectRoot ?? resolveProjectRoot();
23
+ const envConfig = process.env.ZHIN_CONFIG?.trim();
24
+ if (envConfig) return path.resolve(root, envConfig);
25
+ for (const ext of YAML_EXTENSIONS) {
26
+ const candidate = path.join(root, `${CONFIG_BASENAME}${ext}`);
27
+ if (fs.existsSync(candidate)) return candidate;
28
+ }
29
+ for (const ext of ['.json', '.toml', '.ts'] as const) {
30
+ const candidate = path.join(root, `${CONFIG_BASENAME}${ext}`);
31
+ if (fs.existsSync(candidate)) {
32
+ throw new Error(`暂不支持写入 ${ext} 配置文件,请手动在 ${CONFIG_BASENAME}${ext} 的 plugins.qq.endpoints 中维护`);
33
+ }
34
+ }
35
+ return path.join(root, `${CONFIG_BASENAME}.yml`);
36
+ }
37
+
38
+ interface QqConfigDocument {
39
+ filePath: string;
40
+ doc: ReturnType<typeof parseDocument>;
41
+ }
42
+
43
+ function readConfigDocument(projectRoot?: string): QqConfigDocument {
44
+ const filePath = findQqConfigFile(projectRoot);
45
+ const content = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf-8') : '';
46
+ const doc = parseDocument(content || '{}');
47
+ return { filePath, doc };
48
+ }
49
+
50
+ function writeConfigDocument({ filePath, doc }: QqConfigDocument): void {
51
+ fs.writeFileSync(filePath, doc.toString());
52
+ }
53
+
54
+ /** 读取 plugins.qq.endpoints(plain JS);plugins/qq 缺失或形态不符时返回 [] */
55
+ export function listQqEndpointEntries(projectRoot?: string): QqEndpointConfigEntry[] {
56
+ const { doc } = readConfigDocument(projectRoot);
57
+ const plugins = doc.toJS()?.plugins;
58
+ if (!plugins || typeof plugins !== 'object' || Array.isArray(plugins)) return [];
59
+ const endpoints = (plugins as { qq?: { endpoints?: unknown } }).qq?.endpoints;
60
+ if (!Array.isArray(endpoints)) return [];
61
+ return endpoints.filter(
62
+ (entry): entry is QqEndpointConfigEntry =>
63
+ !!entry && typeof entry === 'object' && typeof (entry as { name?: unknown }).name === 'string',
64
+ );
65
+ }
66
+
67
+ function entryName(item: unknown): string | undefined {
68
+ if (!isMap(item)) return undefined;
69
+ const name = item.get('name');
70
+ return typeof name === 'string' && name ? name : undefined;
71
+ }
72
+
73
+ /**
74
+ * 确保 plugins.qq.endpoints 存在并返回其 YAMLSeq(节点级操作,保留既有条目与注释)。
75
+ * `plugins: []`(legacy 空列表,Runtime 忽略)可直接替换为 map;非空数组拒绝写入。
76
+ */
77
+ function ensureEndpointsSeq(doc: ReturnType<typeof parseDocument>): YAMLSeq {
78
+ const plugins = doc.get('plugins');
79
+ if (isSeq(plugins) && plugins.items.length > 0) {
80
+ throw new Error('配置的 plugins 是数组形态(legacy 插件名列表),请手动迁移为 map 后再试');
81
+ }
82
+ if (plugins !== undefined && !isMap(plugins) && !isSeq(plugins)) {
83
+ throw new Error('配置的 plugins 字段形态异常,请手动检查 zhin.config.yml');
84
+ }
85
+ if (!isMap(doc.get('plugins'))) {
86
+ // 注意:空对象 {} 不会被 doc.set 自动包装为 YAMLMap,必须显式 createNode
87
+ doc.set('plugins', doc.createNode({}));
88
+ }
89
+ const qq = doc.getIn(['plugins', 'qq']);
90
+ if (qq !== undefined && !isMap(qq)) {
91
+ throw new Error('配置的 plugins.qq 字段形态异常,请手动检查 zhin.config.yml');
92
+ }
93
+ if (!isMap(doc.getIn(['plugins', 'qq']))) {
94
+ doc.setIn(['plugins', 'qq'], doc.createNode({}));
95
+ }
96
+ const endpoints = doc.getIn(['plugins', 'qq', 'endpoints']);
97
+ if (endpoints !== undefined && !isSeq(endpoints)) {
98
+ throw new Error('配置的 plugins.qq.endpoints 字段形态异常,请手动检查 zhin.config.yml');
99
+ }
100
+ if (!isSeq(doc.getIn(['plugins', 'qq', 'endpoints']))) {
101
+ doc.setIn(['plugins', 'qq', 'endpoints'], doc.createNode([]));
102
+ }
103
+ return doc.getIn(['plugins', 'qq', 'endpoints']) as YAMLSeq;
104
+ }
105
+
106
+ /** 追加 endpoint 到 plugins.qq.endpoints;name 已存在时报错 */
107
+ export function addQqEndpointToConfig(
108
+ entry: QqEndpointConfigEntry,
109
+ projectRoot?: string,
110
+ ): string {
111
+ const document = readConfigDocument(projectRoot);
112
+ const seq = ensureEndpointsSeq(document.doc);
113
+ if (seq.items.some((item) => entryName(item) === entry.name)) {
114
+ throw new Error(`配置中已存在 qq endpoint「${entry.name}」,可先 qq endpoint remove ${entry.name} 再重新添加`);
115
+ }
116
+ seq.items.push(document.doc.createNode(entry));
117
+ writeConfigDocument(document);
118
+ return document.filePath;
119
+ }
120
+
121
+ /** 按 name 移除 plugins.qq.endpoints 项;不存在返回 false */
122
+ export function removeQqEndpointFromConfig(
123
+ name: string,
124
+ projectRoot?: string,
125
+ ): { removed: boolean; filePath: string } {
126
+ const document = readConfigDocument(projectRoot);
127
+ const seq = ensureEndpointsSeq(document.doc);
128
+ const next = seq.items.filter((item) => entryName(item) !== name);
129
+ if (next.length === seq.items.length) {
130
+ return { removed: false, filePath: document.filePath };
131
+ }
132
+ seq.items = next;
133
+ writeConfigDocument(document);
134
+ return { removed: true, filePath: document.filePath };
135
+ }
@@ -0,0 +1,36 @@
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
+
8
+ export interface QqRunningEndpoint {
9
+ name: string;
10
+ mode: string;
11
+ }
12
+
13
+ export interface QqBindFlowHandle {
14
+ /** 绑定期望的 endpoint 名(未指定时为 undefined,成功后取 appId) */
15
+ name?: string;
16
+ stop: () => void;
17
+ }
18
+
19
+ export interface QqRuntimeState {
20
+ /** 当前 generation 已成功创建的 endpoint(name → 描述) */
21
+ readonly endpoints: Map<string, QqRunningEndpoint>;
22
+ /** 全局单例:同一时间只允许一个扫码绑定流程 */
23
+ bindFlow: QqBindFlowHandle | null;
24
+ }
25
+
26
+ export function createQqRuntimeState(): QqRuntimeState {
27
+ return {
28
+ endpoints: new Map(),
29
+ bindFlow: null,
30
+ };
31
+ }
32
+
33
+ export const qqRuntimeStateToken = createToken<QqRuntimeState>(
34
+ 'zhin.qq.runtime-state',
35
+ 'QQ adapter runtime state (running endpoints + bind flow singleton)',
36
+ );