mirror of
https://github.com/hansjone/dsh-im-ops.git
synced 2026-10-10 13:10:44 +08:00
Add QQ bot channel
This commit is contained in:
parent
a422084eb5
commit
601271a7f8
33 changed files with 4971 additions and 642 deletions
171
src/channels/qq/config-store.mjs
Normal file
171
src/channels/qq/config-store.mjs
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
||||
import { dirname } from 'node:path';
|
||||
|
||||
const EMPTY_DOCUMENT = Object.freeze({ version: 1, bots: Object.freeze([]) });
|
||||
|
||||
function cleanString(value) {
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
||||
}
|
||||
|
||||
function safeBotId(value) {
|
||||
const id = cleanString(value);
|
||||
return id && /^qq_[a-f0-9]{24}$/.test(id) ? id : null;
|
||||
}
|
||||
|
||||
function safeSecretRef(value) {
|
||||
const ref = cleanString(value);
|
||||
return ref && /^DSH_QQBOT_APP_SECRET_[A-F0-9]{24}$/.test(ref) ? ref : null;
|
||||
}
|
||||
|
||||
export function deriveQqBotIdentity(appId) {
|
||||
const raw = cleanString(appId);
|
||||
if (!raw) throw new TypeError('appId is required');
|
||||
const digest = createHash('sha256').update(raw).digest('hex').slice(0, 24);
|
||||
return {
|
||||
botId: `qq_${digest}`,
|
||||
secretRef: `DSH_QQBOT_APP_SECRET_${digest.toUpperCase()}`,
|
||||
};
|
||||
}
|
||||
|
||||
export function maskQqAppId(appId) {
|
||||
const value = cleanString(appId) ?? '';
|
||||
if (value.length <= 10) return value ? `${value.slice(0, 3)}•••` : 'QQ机器人';
|
||||
return `${value.slice(0, 6)}••••${value.slice(-4)}`;
|
||||
}
|
||||
|
||||
function normalizeBot(value) {
|
||||
if (!value || typeof value !== 'object') return null;
|
||||
const appId = cleanString(value.appId);
|
||||
const ownerUserOpenid = cleanString(value.ownerUserOpenid);
|
||||
const botId = safeBotId(value.botId);
|
||||
const secretRef = safeSecretRef(value.secretRef);
|
||||
if (!appId || !ownerUserOpenid || !botId || !secretRef) return null;
|
||||
const derived = deriveQqBotIdentity(appId);
|
||||
if (derived.botId !== botId || derived.secretRef !== secretRef) return null;
|
||||
return Object.freeze({
|
||||
botId,
|
||||
appId,
|
||||
secretRef,
|
||||
ownerUserOpenid,
|
||||
createdAt: cleanString(value.createdAt) ?? new Date().toISOString(),
|
||||
connectedAt: cleanString(value.connectedAt),
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeDocument(value) {
|
||||
if (!value || value.version !== 1 || !Array.isArray(value.bots)) return null;
|
||||
const bots = value.bots.map(normalizeBot);
|
||||
if (bots.some((bot) => bot === null)) return null;
|
||||
const ids = new Set();
|
||||
const appIds = new Set();
|
||||
const refs = new Set();
|
||||
for (const bot of bots) {
|
||||
if (ids.has(bot.botId) || appIds.has(bot.appId) || refs.has(bot.secretRef)) return null;
|
||||
ids.add(bot.botId);
|
||||
appIds.add(bot.appId);
|
||||
refs.add(bot.secretRef);
|
||||
}
|
||||
return Object.freeze({ version: 1, bots: Object.freeze(bots) });
|
||||
}
|
||||
|
||||
export class QqConfigStore {
|
||||
#path;
|
||||
#value = EMPTY_DOCUMENT;
|
||||
#writeQueue = Promise.resolve();
|
||||
|
||||
constructor(path) {
|
||||
this.#path = path;
|
||||
}
|
||||
|
||||
async load() {
|
||||
try {
|
||||
const normalized = normalizeDocument(JSON.parse(await readFile(this.#path, 'utf8')));
|
||||
if (!normalized) throw new Error('dsh-im QQ config contains invalid bot data');
|
||||
this.#value = normalized;
|
||||
} catch (error) {
|
||||
if (error?.code !== 'ENOENT') throw error;
|
||||
this.#value = EMPTY_DOCUMENT;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
list() {
|
||||
return structuredClone(this.#value.bots);
|
||||
}
|
||||
|
||||
get(botId) {
|
||||
const bot = this.#value.bots.find((candidate) => candidate.botId === botId);
|
||||
return bot ? structuredClone(bot) : null;
|
||||
}
|
||||
|
||||
getByAppId(appId) {
|
||||
const bot = this.#value.bots.find((candidate) => candidate.appId === appId);
|
||||
return bot ? structuredClone(bot) : null;
|
||||
}
|
||||
|
||||
async save(value) {
|
||||
const normalized = normalizeBot(value);
|
||||
if (!normalized) throw new Error('Refusing to persist incomplete QQ bot data');
|
||||
return this.#mutate((bots) => {
|
||||
const appCollision = bots.find(
|
||||
(bot) => bot.appId === normalized.appId && bot.botId !== normalized.botId,
|
||||
);
|
||||
const refCollision = bots.find(
|
||||
(bot) => bot.secretRef === normalized.secretRef && bot.botId !== normalized.botId,
|
||||
);
|
||||
if (appCollision || refCollision) throw new Error('Duplicate QQ bot identity');
|
||||
const index = bots.findIndex((bot) => bot.botId === normalized.botId);
|
||||
if (index === -1) bots.push(normalized);
|
||||
else bots[index] = normalized;
|
||||
return structuredClone(normalized);
|
||||
});
|
||||
}
|
||||
|
||||
async remove(botId) {
|
||||
if (!safeBotId(botId)) throw new TypeError('Invalid QQ bot id');
|
||||
return this.#mutate((bots) => {
|
||||
const index = bots.findIndex((bot) => bot.botId === botId);
|
||||
if (index === -1) return null;
|
||||
const [removed] = bots.splice(index, 1);
|
||||
return structuredClone(removed);
|
||||
});
|
||||
}
|
||||
|
||||
async clear() {
|
||||
const operation = this.#writeQueue.then(async () => {
|
||||
try {
|
||||
await unlink(this.#path);
|
||||
} catch (error) {
|
||||
if (error?.code !== 'ENOENT') throw error;
|
||||
}
|
||||
this.#value = EMPTY_DOCUMENT;
|
||||
});
|
||||
this.#writeQueue = operation.then(() => undefined, () => undefined);
|
||||
await operation;
|
||||
}
|
||||
|
||||
async #mutate(mutator) {
|
||||
let result;
|
||||
const operation = this.#writeQueue.then(async () => {
|
||||
const bots = [...this.#value.bots];
|
||||
result = mutator(bots);
|
||||
const document = Object.freeze({ version: 1, bots: Object.freeze(bots) });
|
||||
await this.#write(document);
|
||||
this.#value = document;
|
||||
});
|
||||
this.#writeQueue = operation.then(() => undefined, () => undefined);
|
||||
await operation;
|
||||
return result;
|
||||
}
|
||||
|
||||
async #write(document) {
|
||||
await mkdir(dirname(this.#path), { recursive: true, mode: 0o700 });
|
||||
const temporary = `${this.#path}.tmp`;
|
||||
await writeFile(temporary, `${JSON.stringify(document, null, 2)}\n`, {
|
||||
encoding: 'utf8',
|
||||
mode: 0o600,
|
||||
});
|
||||
await rename(temporary, this.#path);
|
||||
}
|
||||
}
|
||||
3
src/channels/qq/harness-client.mjs
Normal file
3
src/channels/qq/harness-client.mjs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import { HarnessClient } from '../weixin/harness-client.mjs';
|
||||
|
||||
export class QqHarnessClient extends HarnessClient {}
|
||||
177
src/channels/qq/qq-bridge.mjs
Normal file
177
src/channels/qq/qq-bridge.mjs
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
const HELP_TEXT = [
|
||||
'QQ 机器人已连接 DeepSeek Harness。',
|
||||
'',
|
||||
'直接发送文字即可继续当前会话。',
|
||||
'/new 开启一个全新会话',
|
||||
'/status 检查连接状态',
|
||||
'/help 显示本帮助',
|
||||
].join('\n');
|
||||
|
||||
function conversationKey(message) {
|
||||
return `${message.kind}:${message.kind === 'group' ? message.groupOpenid : message.senderId}`;
|
||||
}
|
||||
|
||||
function safeText(message) {
|
||||
return typeof message?.content === 'string' ? message.content.trim() : '';
|
||||
}
|
||||
|
||||
export function createQqBridgeStatus() {
|
||||
return {
|
||||
messagesReceived: 0,
|
||||
messagesReplied: 0,
|
||||
messagesRejected: 0,
|
||||
lastMessageAt: null,
|
||||
lastReplyAt: null,
|
||||
lastRejectedAt: null,
|
||||
lastError: null,
|
||||
};
|
||||
}
|
||||
|
||||
export class QqHarnessBridge {
|
||||
#bot;
|
||||
#ownerUserOpenid;
|
||||
#harness;
|
||||
#state;
|
||||
#status;
|
||||
#logger;
|
||||
#replyTimeoutMs;
|
||||
#queues = new Map();
|
||||
|
||||
constructor({
|
||||
bot,
|
||||
ownerUserOpenid,
|
||||
harness,
|
||||
state,
|
||||
status = createQqBridgeStatus(),
|
||||
logger = console,
|
||||
replyTimeoutMs = 600_000,
|
||||
}) {
|
||||
if (!bot || typeof bot.sendText !== 'function') throw new TypeError('QQ bot client is required');
|
||||
if (!ownerUserOpenid) throw new TypeError('QQ scanner identity is required');
|
||||
if (!harness || !state) throw new TypeError('Harness client and state store are required');
|
||||
this.#bot = bot;
|
||||
this.#ownerUserOpenid = ownerUserOpenid;
|
||||
this.#harness = harness;
|
||||
this.#state = state;
|
||||
this.#status = status;
|
||||
this.#logger = logger;
|
||||
this.#replyTimeoutMs = replyTimeoutMs;
|
||||
}
|
||||
|
||||
get status() {
|
||||
return structuredClone(this.#status);
|
||||
}
|
||||
|
||||
accept(message) {
|
||||
const key = conversationKey(message);
|
||||
const previous = this.#queues.get(key) ?? Promise.resolve();
|
||||
const current = previous
|
||||
.catch(() => undefined)
|
||||
.then(() => this.#process(message))
|
||||
.finally(() => {
|
||||
if (this.#queues.get(key) === current) this.#queues.delete(key);
|
||||
});
|
||||
this.#queues.set(key, current);
|
||||
return current;
|
||||
}
|
||||
|
||||
async waitForIdle() {
|
||||
await Promise.allSettled([...this.#queues.values()]);
|
||||
}
|
||||
|
||||
async #process(message) {
|
||||
const messageId = typeof message?.messageId === 'string' ? message.messageId : '';
|
||||
const sender = typeof message?.senderId === 'string' ? message.senderId : '';
|
||||
if (!messageId || !sender || message.senderIsBot === true) return;
|
||||
if (!['c2c', 'group'].includes(message.kind) || this.#state.hasSeen(messageId)) return;
|
||||
|
||||
this.#status.messagesReceived += 1;
|
||||
this.#status.lastMessageAt = new Date().toISOString();
|
||||
if (sender !== this.#ownerUserOpenid) {
|
||||
this.#status.messagesRejected += 1;
|
||||
this.#status.lastRejectedAt = new Date().toISOString();
|
||||
return;
|
||||
}
|
||||
if (message.kind === 'group' && message.rawEventType !== 'GROUP_AT_MESSAGE_CREATE') return;
|
||||
|
||||
const target = message.replyTarget;
|
||||
const text = safeText(message);
|
||||
try {
|
||||
if (!text) {
|
||||
await this.#bot.sendText(target, '目前仅支持文字消息。');
|
||||
await this.#state.markSeen(messageId);
|
||||
return;
|
||||
}
|
||||
const command = text.toLowerCase();
|
||||
if (command === '/help') {
|
||||
await this.#bot.sendText(target, HELP_TEXT);
|
||||
await this.#state.markSeen(messageId);
|
||||
return;
|
||||
}
|
||||
if (command === '/status') {
|
||||
await this.#harness.ensureRunning();
|
||||
await this.#bot.sendText(target, 'QQ 机器人与 DeepSeek Harness 连接正常。');
|
||||
await this.#state.markSeen(messageId);
|
||||
return;
|
||||
}
|
||||
const key = conversationKey(message);
|
||||
if (command === '/new') {
|
||||
await this.#state.clearSession(key);
|
||||
await this.#bot.sendText(target, '已开启新会话。请发送你的问题。');
|
||||
await this.#state.markSeen(messageId);
|
||||
return;
|
||||
}
|
||||
|
||||
let sessionId = this.#state.sessionFor(key);
|
||||
if (!sessionId || !(await this.#harness.sessionExists(sessionId))) {
|
||||
sessionId = await this.#harness.createSession();
|
||||
await this.#state.setSession(key, sessionId);
|
||||
}
|
||||
|
||||
let stream = null;
|
||||
let streamFinished = false;
|
||||
if (message.kind === 'c2c' && target?.msgId && typeof this.#bot.openStream === 'function') {
|
||||
try {
|
||||
stream = this.#bot.openStream({ target });
|
||||
} catch (error) {
|
||||
this.#logger.warn?.('[dsh-im:qq] unable to start a QQ stream; using a text reply:', error);
|
||||
}
|
||||
}
|
||||
const answer = await this.#harness.ask(sessionId, text, {
|
||||
timeoutMs: this.#replyTimeoutMs,
|
||||
onUpdate: stream ? async (update) => {
|
||||
const progress = update.type === 'text'
|
||||
? update.text
|
||||
: update.type === 'tool'
|
||||
? `正在使用${update.name}…`
|
||||
: update.text;
|
||||
if (progress) await stream.update(progress);
|
||||
} : undefined,
|
||||
});
|
||||
if (stream) {
|
||||
try {
|
||||
await stream.update(answer);
|
||||
await stream.complete();
|
||||
streamFinished = true;
|
||||
} catch (error) {
|
||||
stream.cancel?.();
|
||||
this.#logger.warn?.('[dsh-im:qq] QQ stream finalization failed; using a text reply:', error);
|
||||
}
|
||||
}
|
||||
if (!streamFinished) await this.#bot.sendText(target, answer);
|
||||
await this.#state.markSeen(messageId);
|
||||
this.#status.messagesReplied += 1;
|
||||
this.#status.lastReplyAt = new Date().toISOString();
|
||||
this.#status.lastError = null;
|
||||
} catch (error) {
|
||||
this.#status.lastError = error?.message ?? String(error);
|
||||
this.#logger.error?.('[dsh-im:qq] failed to process an inbound message:', error);
|
||||
try {
|
||||
await this.#bot.sendText(target, '消息处理失败,请稍后重试。');
|
||||
await this.#state.markSeen(messageId);
|
||||
} catch (sendError) {
|
||||
this.#logger.error?.('[dsh-im:qq] failed to send the safe error reply:', sendError);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
407
src/channels/qq/qq-controller.mjs
Normal file
407
src/channels/qq/qq-controller.mjs
Normal file
|
|
@ -0,0 +1,407 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
import { deriveQqBotIdentity, maskQqAppId } from './config-store.mjs';
|
||||
|
||||
const ACTIVE_ATTEMPT_STATES = new Set(['starting', 'pending', 'refreshing', 'connecting']);
|
||||
const TERMINAL_ATTEMPT_STATES = new Set(['connected', 'failed', 'cancelled']);
|
||||
const QR_TTL_MS = 5 * 60_000;
|
||||
|
||||
function cleanString(value) {
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
||||
}
|
||||
|
||||
function safeError(code, message) {
|
||||
return Object.freeze({ code, message });
|
||||
}
|
||||
|
||||
function publicAttempt(record) {
|
||||
if (!record) return null;
|
||||
return {
|
||||
attemptId: record.id,
|
||||
status: record.state,
|
||||
qrRevision: record.qrRevision,
|
||||
pollIntervalMs: 1_000,
|
||||
...(record.verificationUrl ? { verificationUrl: record.verificationUrl } : {}),
|
||||
...(record.expiresAt ? { expiresAt: record.expiresAt } : {}),
|
||||
...(record.botId ? { botId: record.botId } : {}),
|
||||
...(record.error ? { error: structuredClone(record.error) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export class QqController {
|
||||
#qrAuth;
|
||||
#credentials;
|
||||
#configStore;
|
||||
#createRuntime;
|
||||
#deleteState;
|
||||
#logger;
|
||||
#runtimes = new Map();
|
||||
#errors = new Map();
|
||||
#attempts = new Map();
|
||||
#activeAttemptId = null;
|
||||
#transitions = new Map();
|
||||
#revision = 0;
|
||||
#closed = false;
|
||||
|
||||
constructor({
|
||||
qrAuth,
|
||||
credentials,
|
||||
configStore,
|
||||
createRuntime,
|
||||
deleteState = async () => {},
|
||||
logger = console,
|
||||
}) {
|
||||
if (!qrAuth || typeof qrAuth.start !== 'function') throw new TypeError('QQ QR auth is required');
|
||||
if (!credentials || typeof credentials.resolve !== 'function'
|
||||
|| typeof credentials.set !== 'function' || typeof credentials.unset !== 'function') {
|
||||
throw new TypeError('QqController requires the DSH credential provider');
|
||||
}
|
||||
if (!configStore || typeof configStore.list !== 'function'
|
||||
|| typeof configStore.save !== 'function' || typeof configStore.remove !== 'function') {
|
||||
throw new TypeError('QqController requires a config store');
|
||||
}
|
||||
if (typeof createRuntime !== 'function') throw new TypeError('createRuntime is required');
|
||||
this.#qrAuth = qrAuth;
|
||||
this.#credentials = credentials;
|
||||
this.#configStore = configStore;
|
||||
this.#createRuntime = createRuntime;
|
||||
this.#deleteState = deleteState;
|
||||
this.#logger = logger;
|
||||
}
|
||||
|
||||
async initialize() {
|
||||
if (this.#closed) return this.status();
|
||||
for (const config of this.#configStore.list()) {
|
||||
await this.#withBotTransition(config.botId, async () => {
|
||||
if (this.#closed || this.#runtimes.get(config.botId)?.status?.ready) return;
|
||||
const appSecret = await this.#resolveSecret(config.secretRef);
|
||||
if (!appSecret) {
|
||||
this.#errors.set(config.botId, safeError('missing-secret', 'QQ 机器人凭据缺失,请移除后重新扫码。'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await this.#startRuntime(config, appSecret);
|
||||
this.#errors.delete(config.botId);
|
||||
} catch (error) {
|
||||
this.#errors.set(config.botId, safeError('connection-failed', 'QQ 连接未就绪,插件会自动重试。'));
|
||||
this.#logger.warn?.(`[dsh-im:qq] bot ${config.botId} failed to initialize:`, error);
|
||||
} finally {
|
||||
this.#touch();
|
||||
}
|
||||
});
|
||||
}
|
||||
return this.status();
|
||||
}
|
||||
|
||||
async startProvisioning() {
|
||||
if (this.#closed) throw new Error('QQ controller is closed');
|
||||
if (this.#activeAttemptId) await this.cancelProvisioning(this.#activeAttemptId);
|
||||
let firstQrResolve;
|
||||
let firstQrReject;
|
||||
const firstQr = new Promise((resolve, reject) => {
|
||||
firstQrResolve = resolve;
|
||||
firstQrReject = reject;
|
||||
});
|
||||
const record = {
|
||||
id: randomUUID(),
|
||||
state: 'starting',
|
||||
createdAt: Date.now(),
|
||||
expiresAt: null,
|
||||
qrRevision: 0,
|
||||
verificationUrl: null,
|
||||
controller: new AbortController(),
|
||||
dispose: null,
|
||||
task: null,
|
||||
error: null,
|
||||
botId: null,
|
||||
};
|
||||
this.#attempts.set(record.id, record);
|
||||
this.#activeAttemptId = record.id;
|
||||
this.#touch();
|
||||
|
||||
try {
|
||||
record.dispose = this.#qrAuth.start({
|
||||
onQrDisplayed: (url) => {
|
||||
if (record.controller.signal.aborted || TERMINAL_ATTEMPT_STATES.has(record.state)) return;
|
||||
const verificationUrl = cleanString(url);
|
||||
if (!verificationUrl) return;
|
||||
record.verificationUrl = verificationUrl;
|
||||
record.qrRevision += 1;
|
||||
record.expiresAt = Date.now() + QR_TTL_MS;
|
||||
record.state = 'pending';
|
||||
this.#touch();
|
||||
firstQrResolve();
|
||||
},
|
||||
onQrExpired: () => {
|
||||
if (record.controller.signal.aborted || TERMINAL_ATTEMPT_STATES.has(record.state)) return;
|
||||
record.state = 'refreshing';
|
||||
record.verificationUrl = null;
|
||||
record.expiresAt = null;
|
||||
this.#touch();
|
||||
},
|
||||
onSuccess: (credentials) => {
|
||||
if (record.controller.signal.aborted || TERMINAL_ATTEMPT_STATES.has(record.state)) return;
|
||||
record.task = this.#completeProvisioning(record, credentials);
|
||||
},
|
||||
onFailure: (error) => {
|
||||
if (record.controller.signal.aborted || TERMINAL_ATTEMPT_STATES.has(record.state)) return;
|
||||
record.state = 'failed';
|
||||
record.error = safeError('qr-connect-failed', 'QQ 扫码服务暂时不可用,请重新生成二维码。');
|
||||
if (this.#activeAttemptId === record.id) this.#activeAttemptId = null;
|
||||
this.#touch();
|
||||
firstQrReject(error);
|
||||
},
|
||||
}, { signal: record.controller.signal });
|
||||
await firstQr;
|
||||
return publicAttempt(record);
|
||||
} catch (error) {
|
||||
if (record.controller.signal.aborted) {
|
||||
record.state = 'cancelled';
|
||||
record.error = safeError('cancelled', '扫码绑定已取消。');
|
||||
} else if (!TERMINAL_ATTEMPT_STATES.has(record.state)) {
|
||||
record.state = 'failed';
|
||||
record.error = safeError('qr-start-failed', '无法生成 QQ 二维码,请稍后重试。');
|
||||
}
|
||||
if (this.#activeAttemptId === record.id) this.#activeAttemptId = null;
|
||||
this.#touch();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
registrationStatus(attemptId) {
|
||||
return publicAttempt(this.#attempts.get(attemptId));
|
||||
}
|
||||
|
||||
async cancelProvisioning(attemptId) {
|
||||
const record = this.#attempts.get(attemptId);
|
||||
if (!record) return null;
|
||||
if (!TERMINAL_ATTEMPT_STATES.has(record.state)) {
|
||||
record.controller.abort();
|
||||
record.dispose?.();
|
||||
await record.task?.catch(() => undefined);
|
||||
if (!TERMINAL_ATTEMPT_STATES.has(record.state)) record.state = 'cancelled';
|
||||
record.error ??= safeError('cancelled', '扫码绑定已取消。');
|
||||
}
|
||||
if (this.#activeAttemptId === record.id) this.#activeAttemptId = null;
|
||||
this.#touch();
|
||||
return publicAttempt(record);
|
||||
}
|
||||
|
||||
async reconnectBot(botId) {
|
||||
const config = this.#configStore.get(botId);
|
||||
if (!config) throw new Error('Unknown QQ bot');
|
||||
await this.#withBotTransition(botId, async () => {
|
||||
const secret = await this.#resolveSecret(config.secretRef);
|
||||
if (!secret) throw new Error('QQ bot secret is missing');
|
||||
try {
|
||||
await this.#startRuntime(config, secret);
|
||||
this.#errors.delete(botId);
|
||||
} catch (error) {
|
||||
this.#errors.set(botId, safeError('connection-failed', 'QQ 连接仍未就绪,请稍后重试。'));
|
||||
throw error;
|
||||
} finally {
|
||||
this.#touch();
|
||||
}
|
||||
});
|
||||
return this.status();
|
||||
}
|
||||
|
||||
async deleteBot(botId) {
|
||||
const config = this.#configStore.get(botId);
|
||||
if (!config) throw new Error('Unknown QQ bot');
|
||||
await this.#withBotTransition(botId, async () => {
|
||||
const previous = await this.#credentials.resolve(config.secretRef).catch(() => undefined);
|
||||
await this.#stopRuntime(botId);
|
||||
try {
|
||||
await this.#credentials.unset(config.secretRef);
|
||||
await this.#configStore.remove(botId);
|
||||
} catch (error) {
|
||||
if (previous?.value) {
|
||||
await this.#credentials.set(config.secretRef, previous.value).catch(() => undefined);
|
||||
await this.#startRuntime(config, previous.value).catch(() => undefined);
|
||||
}
|
||||
throw new Error('Unable to remove the QQ bot safely.', { cause: error });
|
||||
}
|
||||
await this.#deleteState({ botId, config }).catch((error) => {
|
||||
this.#logger.warn?.(`[dsh-im:qq] bot ${botId} state cleanup failed:`, error);
|
||||
});
|
||||
this.#errors.delete(botId);
|
||||
this.#touch();
|
||||
});
|
||||
return this.status();
|
||||
}
|
||||
|
||||
status() {
|
||||
const bots = this.#configStore.list().map((config) => {
|
||||
const runtimeStatus = this.#runtimes.get(config.botId)?.status ?? null;
|
||||
const connected = runtimeStatus?.ready === true
|
||||
&& runtimeStatus.qqConnectionState === 'connected'
|
||||
&& runtimeStatus.harnessReachable === true;
|
||||
const state = connected ? 'connected'
|
||||
: runtimeStatus?.qqConnectionState === 'connecting' ? 'connecting'
|
||||
: this.#errors.has(config.botId) || runtimeStatus?.qqConnectionState === 'failed'
|
||||
? 'error' : 'offline';
|
||||
return {
|
||||
botId: config.botId,
|
||||
state,
|
||||
connected,
|
||||
configured: true,
|
||||
bot: { name: 'QQ机器人', appIdMasked: maskQqAppId(config.appId) },
|
||||
health: {
|
||||
status: connected ? 'healthy' : state === 'error' ? 'error' : 'offline',
|
||||
summary: connected ? 'QQ WebSocket 长连接运行正常'
|
||||
: state === 'error' ? 'QQ 连接未就绪,插件会自动重试' : 'QQ 连接当前离线',
|
||||
lastCheckedAt: runtimeStatus?.lastCheckedAt ?? null,
|
||||
lastConnectedAt: runtimeStatus?.lastConnectedAt ?? null,
|
||||
},
|
||||
stats: {
|
||||
messagesReceived: runtimeStatus?.messagesReceived ?? 0,
|
||||
messagesReplied: runtimeStatus?.messagesReplied ?? 0,
|
||||
},
|
||||
error: structuredClone(this.#errors.get(config.botId) ?? null),
|
||||
};
|
||||
});
|
||||
const connectedCount = bots.filter((bot) => bot.connected).length;
|
||||
const active = this.#activeAttemptId ? this.#attempts.get(this.#activeAttemptId) : null;
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
revision: this.#revision,
|
||||
state: active && ACTIVE_ATTEMPT_STATES.has(active.state) ? 'provisioning'
|
||||
: bots.length === 0 ? 'disconnected'
|
||||
: connectedCount === bots.length ? 'connected'
|
||||
: connectedCount > 0 ? 'degraded' : 'offline',
|
||||
bots,
|
||||
totals: { configured: bots.length, connected: connectedCount },
|
||||
...(active && ACTIVE_ATTEMPT_STATES.has(active.state)
|
||||
? { provisioning: publicAttempt(active) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async close() {
|
||||
if (this.#closed) return;
|
||||
this.#closed = true;
|
||||
if (this.#activeAttemptId) await this.cancelProvisioning(this.#activeAttemptId);
|
||||
await Promise.allSettled([...this.#runtimes.keys()].map((botId) => this.#stopRuntime(botId)));
|
||||
}
|
||||
|
||||
async #completeProvisioning(record, credentials) {
|
||||
try {
|
||||
record.state = 'connecting';
|
||||
record.verificationUrl = null;
|
||||
record.expiresAt = null;
|
||||
this.#touch();
|
||||
const credential = Array.isArray(credentials) ? credentials[0] : null;
|
||||
const appId = cleanString(credential?.appId);
|
||||
const appSecret = cleanString(credential?.appSecret);
|
||||
const ownerUserOpenid = cleanString(credential?.userOpenid);
|
||||
if (!appId || !appSecret || !ownerUserOpenid) {
|
||||
throw new Error('QQ authorization returned incomplete credentials');
|
||||
}
|
||||
record.botId = await this.#activateBot(record, { appId, appSecret, ownerUserOpenid });
|
||||
record.state = 'connected';
|
||||
record.error = null;
|
||||
} catch (error) {
|
||||
if (record.controller.signal.aborted) {
|
||||
record.state = 'cancelled';
|
||||
record.error = safeError('cancelled', '扫码绑定已取消。');
|
||||
} else {
|
||||
record.state = 'failed';
|
||||
record.error = safeError('activation-failed', 'QQ 已授权,但无法安全保存接入配置。');
|
||||
this.#logger.error?.('[dsh-im:qq] provisioning failed:', error);
|
||||
}
|
||||
} finally {
|
||||
record.dispose?.();
|
||||
if (this.#activeAttemptId === record.id) this.#activeAttemptId = null;
|
||||
this.#touch();
|
||||
}
|
||||
}
|
||||
|
||||
async #activateBot(record, { appId, appSecret, ownerUserOpenid }) {
|
||||
const identity = deriveQqBotIdentity(appId);
|
||||
const previousConfig = this.#configStore.getByAppId(appId);
|
||||
const previousSecret = await this.#credentials.resolve(identity.secretRef).catch(() => undefined);
|
||||
const config = {
|
||||
botId: identity.botId,
|
||||
appId,
|
||||
secretRef: identity.secretRef,
|
||||
ownerUserOpenid,
|
||||
createdAt: previousConfig?.createdAt ?? new Date().toISOString(),
|
||||
connectedAt: new Date().toISOString(),
|
||||
};
|
||||
return this.#withBotTransition(identity.botId, async () => {
|
||||
await this.#credentials.set(identity.secretRef, appSecret);
|
||||
try {
|
||||
if (record.controller.signal.aborted) throw new DOMException('Cancelled', 'AbortError');
|
||||
await this.#configStore.save(config);
|
||||
} catch (error) {
|
||||
await this.#restoreCredential(identity.secretRef, previousSecret);
|
||||
throw error;
|
||||
}
|
||||
try {
|
||||
if (record.controller.signal.aborted) throw new DOMException('Cancelled', 'AbortError');
|
||||
await this.#startRuntime(config, appSecret);
|
||||
this.#errors.delete(identity.botId);
|
||||
} catch (error) {
|
||||
if (record.controller.signal.aborted) {
|
||||
await this.#stopRuntime(identity.botId);
|
||||
if (previousConfig) await this.#configStore.save(previousConfig).catch(() => undefined);
|
||||
else await this.#configStore.remove(identity.botId).catch(() => undefined);
|
||||
await this.#restoreCredential(identity.secretRef, previousSecret);
|
||||
throw error;
|
||||
}
|
||||
this.#errors.set(identity.botId, safeError('connection-failed', 'QQ 机器人已绑定,消息连接暂未就绪。'));
|
||||
this.#logger.warn?.(`[dsh-im:qq] bot ${identity.botId} activation connection failed:`, error);
|
||||
}
|
||||
this.#touch();
|
||||
return identity.botId;
|
||||
});
|
||||
}
|
||||
|
||||
async #startRuntime(config, appSecret) {
|
||||
await this.#stopRuntime(config.botId);
|
||||
const runtime = await this.#createRuntime({ botId: config.botId, config, appSecret });
|
||||
if (!runtime || typeof runtime.start !== 'function' || typeof runtime.stop !== 'function') {
|
||||
throw new TypeError('createRuntime returned an invalid QQ runtime');
|
||||
}
|
||||
this.#runtimes.set(config.botId, runtime);
|
||||
try {
|
||||
await runtime.start();
|
||||
} catch (error) {
|
||||
await runtime.stop().catch(() => undefined);
|
||||
this.#runtimes.delete(config.botId);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async #stopRuntime(botId) {
|
||||
const runtime = this.#runtimes.get(botId);
|
||||
this.#runtimes.delete(botId);
|
||||
await runtime?.stop().catch((error) => {
|
||||
this.#logger.warn?.(`[dsh-im:qq] bot ${botId} failed to stop cleanly:`, error);
|
||||
});
|
||||
}
|
||||
|
||||
async #resolveSecret(ref) {
|
||||
const result = await this.#credentials.resolve(ref).catch(() => undefined);
|
||||
return cleanString(result?.value);
|
||||
}
|
||||
|
||||
async #restoreCredential(ref, previous) {
|
||||
if (previous?.value) await this.#credentials.set(ref, previous.value).catch(() => undefined);
|
||||
else await this.#credentials.unset(ref).catch(() => undefined);
|
||||
}
|
||||
|
||||
#withBotTransition(botId, operation) {
|
||||
const previous = this.#transitions.get(botId) ?? Promise.resolve();
|
||||
const current = previous.catch(() => undefined).then(operation);
|
||||
const settled = current.finally(() => {
|
||||
if (this.#transitions.get(botId) === settled) this.#transitions.delete(botId);
|
||||
});
|
||||
this.#transitions.set(botId, settled);
|
||||
return settled;
|
||||
}
|
||||
|
||||
#touch() {
|
||||
this.#revision += 1;
|
||||
}
|
||||
}
|
||||
207
src/channels/qq/qq-runtime.mjs
Normal file
207
src/channels/qq/qq-runtime.mjs
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
import { QQBot, typingIndicator } from '@tencent-connect/qqbot-nodejs';
|
||||
|
||||
import { createQqBridgeStatus, QqHarnessBridge } from './qq-bridge.mjs';
|
||||
|
||||
function timeoutError() {
|
||||
const error = new Error('QQ WebSocket did not become ready in time');
|
||||
error.code = 'connect-timeout';
|
||||
return error;
|
||||
}
|
||||
|
||||
export function createQqRuntimeStatus() {
|
||||
return {
|
||||
startedAt: null,
|
||||
ready: false,
|
||||
qqConnectionState: 'idle',
|
||||
harnessReachable: false,
|
||||
lastCheckedAt: null,
|
||||
lastConnectedAt: null,
|
||||
lastError: null,
|
||||
...createQqBridgeStatus(),
|
||||
};
|
||||
}
|
||||
|
||||
export class QqRuntime {
|
||||
#config;
|
||||
#appSecret;
|
||||
#harness;
|
||||
#state;
|
||||
#logger;
|
||||
#replyTimeoutMs;
|
||||
#connectTimeoutMs;
|
||||
#createBot;
|
||||
#typingMiddleware;
|
||||
#status = createQqRuntimeStatus();
|
||||
#bot = null;
|
||||
#bridge = null;
|
||||
#abortController = null;
|
||||
#runTask = null;
|
||||
#starting = null;
|
||||
|
||||
constructor({
|
||||
config,
|
||||
appSecret,
|
||||
harness,
|
||||
state,
|
||||
logger = console,
|
||||
replyTimeoutMs = 600_000,
|
||||
connectTimeoutMs = 20_000,
|
||||
createBot = (options) => new QQBot(options),
|
||||
typingMiddleware = typingIndicator,
|
||||
}) {
|
||||
if (!config || !appSecret || !harness || !state) {
|
||||
throw new TypeError('QqRuntime requires config, app secret, Harness, and state');
|
||||
}
|
||||
this.#config = config;
|
||||
this.#appSecret = appSecret;
|
||||
this.#harness = harness;
|
||||
this.#state = state;
|
||||
this.#logger = logger;
|
||||
this.#replyTimeoutMs = replyTimeoutMs;
|
||||
this.#connectTimeoutMs = connectTimeoutMs;
|
||||
this.#createBot = createBot;
|
||||
this.#typingMiddleware = typingMiddleware;
|
||||
}
|
||||
|
||||
get status() {
|
||||
return structuredClone(this.#status);
|
||||
}
|
||||
|
||||
async start() {
|
||||
if (this.#status.ready && this.#bot) return this.status;
|
||||
if (this.#starting) return this.#starting;
|
||||
this.#starting = this.#start().finally(() => {
|
||||
this.#starting = null;
|
||||
});
|
||||
return this.#starting;
|
||||
}
|
||||
|
||||
async #start() {
|
||||
await this.stop();
|
||||
this.#status.startedAt = new Date().toISOString();
|
||||
this.#status.qqConnectionState = 'connecting';
|
||||
this.#status.lastError = null;
|
||||
await this.#harness.ensureRunning();
|
||||
this.#status.harnessReachable = true;
|
||||
|
||||
const sdkLogger = {
|
||||
error: (...args) => this.#logger.error?.(...args),
|
||||
warn: (...args) => this.#logger.warn?.(...args),
|
||||
info: (...args) => this.#logger.info?.(...args),
|
||||
debug: () => {},
|
||||
};
|
||||
const bot = this.#createBot({
|
||||
appId: this.#config.appId,
|
||||
appSecret: this.#appSecret,
|
||||
accountId: this.#config.botId,
|
||||
logger: sdkLogger,
|
||||
transport: 'websocket',
|
||||
tokenPrefetch: 'sync',
|
||||
});
|
||||
if (!bot || typeof bot.start !== 'function' || typeof bot.stop !== 'function') {
|
||||
throw new TypeError('QQ bot factory returned an invalid client');
|
||||
}
|
||||
this.#bot = bot;
|
||||
this.#bridge = new QqHarnessBridge({
|
||||
bot,
|
||||
ownerUserOpenid: this.#config.ownerUserOpenid,
|
||||
harness: this.#harness,
|
||||
state: this.#state,
|
||||
status: this.#status,
|
||||
logger: this.#logger,
|
||||
replyTimeoutMs: this.#replyTimeoutMs,
|
||||
});
|
||||
bot.use?.(this.#typingMiddleware({
|
||||
keepAlive: true,
|
||||
predicate: (ctx) => ctx?.message?.senderId === this.#config.ownerUserOpenid,
|
||||
}));
|
||||
|
||||
const controller = new AbortController();
|
||||
this.#abortController = controller;
|
||||
let readyResolve;
|
||||
let readyReject;
|
||||
const ready = new Promise((resolve, reject) => {
|
||||
readyResolve = resolve;
|
||||
readyReject = reject;
|
||||
});
|
||||
const onReady = () => {
|
||||
const now = Date.now();
|
||||
this.#status.ready = true;
|
||||
this.#status.qqConnectionState = 'connected';
|
||||
this.#status.lastCheckedAt = now;
|
||||
this.#status.lastConnectedAt = now;
|
||||
this.#status.lastError = null;
|
||||
readyResolve();
|
||||
};
|
||||
const onError = (error) => {
|
||||
if (!this.#status.ready) readyReject(error);
|
||||
else {
|
||||
this.#status.lastError = error?.message ?? String(error);
|
||||
this.#logger.warn?.(`[dsh-im:qq] bot ${this.#config.botId} connection error:`, error);
|
||||
}
|
||||
};
|
||||
const onMessage = (_ctx, message) => this.#bridge?.accept(message);
|
||||
bot.on('ready', onReady);
|
||||
bot.on('resumed', onReady);
|
||||
bot.on('error', onError);
|
||||
bot.on('message', onMessage);
|
||||
|
||||
const runTask = Promise.resolve().then(() => bot.start(controller.signal));
|
||||
this.#runTask = runTask;
|
||||
runTask.catch((error) => {
|
||||
if (controller.signal.aborted) return;
|
||||
readyReject(error);
|
||||
this.#status.ready = false;
|
||||
this.#status.qqConnectionState = 'failed';
|
||||
this.#status.lastError = error?.message ?? String(error);
|
||||
this.#logger.error?.(`[dsh-im:qq] bot ${this.#config.botId} connection stopped:`, error);
|
||||
});
|
||||
|
||||
let timer;
|
||||
try {
|
||||
await Promise.race([
|
||||
ready,
|
||||
new Promise((_, reject) => {
|
||||
timer = setTimeout(() => reject(timeoutError()), this.#connectTimeoutMs);
|
||||
}),
|
||||
]);
|
||||
this.#status.ready = true;
|
||||
this.#status.qqConnectionState = 'connected';
|
||||
this.#status.lastCheckedAt = Date.now();
|
||||
this.#status.lastConnectedAt = Date.now();
|
||||
return this.status;
|
||||
} catch (error) {
|
||||
this.#status.ready = false;
|
||||
this.#status.qqConnectionState = 'failed';
|
||||
this.#status.lastError = error?.message ?? String(error);
|
||||
await this.stop();
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
async stop() {
|
||||
const bot = this.#bot;
|
||||
const bridge = this.#bridge;
|
||||
const runTask = this.#runTask;
|
||||
this.#abortController?.abort();
|
||||
this.#abortController = null;
|
||||
this.#bot = null;
|
||||
this.#bridge = null;
|
||||
this.#runTask = null;
|
||||
try {
|
||||
bot?.stop();
|
||||
} catch (error) {
|
||||
this.#logger.warn?.(`[dsh-im:qq] bot ${this.#config.botId} failed to stop cleanly:`, error);
|
||||
}
|
||||
await Promise.race([
|
||||
runTask?.catch(() => undefined) ?? Promise.resolve(),
|
||||
new Promise((resolve) => setTimeout(resolve, 2_000)),
|
||||
]);
|
||||
await bridge?.waitForIdle();
|
||||
this.#status.ready = false;
|
||||
this.#status.qqConnectionState = 'idle';
|
||||
return this.status;
|
||||
}
|
||||
}
|
||||
24
src/channels/qq/qr-auth.mjs
Normal file
24
src/channels/qq/qr-auth.mjs
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { startQrConnect } from '@tencent-connect/qqbot-connector';
|
||||
|
||||
export class QqQrAuth {
|
||||
#start;
|
||||
#source;
|
||||
|
||||
constructor({ start = startQrConnect, source = 'deepseek-harness' } = {}) {
|
||||
if (typeof start !== 'function') throw new TypeError('QQ QR connector is required');
|
||||
this.#start = start;
|
||||
this.#source = source;
|
||||
}
|
||||
|
||||
start(callbacks, { signal } = {}) {
|
||||
if (!callbacks || typeof callbacks.onSuccess !== 'function'
|
||||
|| typeof callbacks.onFailure !== 'function') {
|
||||
throw new TypeError('QQ QR callbacks are required');
|
||||
}
|
||||
return this.#start(callbacks, {
|
||||
displayQrCodeToConsole: false,
|
||||
source: this.#source,
|
||||
signal,
|
||||
});
|
||||
}
|
||||
}
|
||||
96
src/channels/qq/state-store.mjs
Normal file
96
src/channels/qq/state-store.mjs
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
||||
import { dirname } from 'node:path';
|
||||
|
||||
const EMPTY_STATE = Object.freeze({ version: 1, sessions: {}, seenMessageIds: [] });
|
||||
|
||||
function normalizeState(value) {
|
||||
if (!value || typeof value !== 'object') return structuredClone(EMPTY_STATE);
|
||||
const sessions = {};
|
||||
if (value.sessions && typeof value.sessions === 'object' && !Array.isArray(value.sessions)) {
|
||||
for (const [key, sessionId] of Object.entries(value.sessions)) {
|
||||
if (typeof key === 'string' && typeof sessionId === 'string' && sessionId) {
|
||||
sessions[key] = sessionId;
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
version: 1,
|
||||
sessions,
|
||||
seenMessageIds: Array.isArray(value.seenMessageIds)
|
||||
? value.seenMessageIds.filter((id) => typeof id === 'string').slice(-1_000)
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
export class QqStateStore {
|
||||
#path;
|
||||
#state = structuredClone(EMPTY_STATE);
|
||||
#writeQueue = Promise.resolve();
|
||||
|
||||
constructor(path) {
|
||||
this.#path = path;
|
||||
}
|
||||
|
||||
async load() {
|
||||
try {
|
||||
this.#state = normalizeState(JSON.parse(await readFile(this.#path, 'utf8')));
|
||||
} catch (error) {
|
||||
if (error?.code !== 'ENOENT') throw error;
|
||||
this.#state = structuredClone(EMPTY_STATE);
|
||||
await this.#persist();
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
sessionFor(key) {
|
||||
return this.#state.sessions[key] ?? null;
|
||||
}
|
||||
|
||||
async setSession(key, sessionId) {
|
||||
this.#state.sessions[key] = sessionId;
|
||||
await this.#persist();
|
||||
}
|
||||
|
||||
async clearSession(key) {
|
||||
delete this.#state.sessions[key];
|
||||
await this.#persist();
|
||||
}
|
||||
|
||||
hasSeen(messageId) {
|
||||
return this.#state.seenMessageIds.includes(messageId);
|
||||
}
|
||||
|
||||
async markSeen(messageId) {
|
||||
if (this.hasSeen(messageId)) return;
|
||||
this.#state.seenMessageIds.push(messageId);
|
||||
if (this.#state.seenMessageIds.length > 1_000) {
|
||||
this.#state.seenMessageIds.splice(0, this.#state.seenMessageIds.length - 1_000);
|
||||
}
|
||||
await this.#persist();
|
||||
}
|
||||
|
||||
snapshot() {
|
||||
return structuredClone(this.#state);
|
||||
}
|
||||
|
||||
async remove() {
|
||||
try {
|
||||
await unlink(this.#path);
|
||||
} catch (error) {
|
||||
if (error?.code !== 'ENOENT') throw error;
|
||||
}
|
||||
this.#state = structuredClone(EMPTY_STATE);
|
||||
}
|
||||
|
||||
async #persist() {
|
||||
const snapshot = `${JSON.stringify(this.#state, null, 2)}\n`;
|
||||
const operation = this.#writeQueue.then(async () => {
|
||||
await mkdir(dirname(this.#path), { recursive: true, mode: 0o700 });
|
||||
const temporary = `${this.#path}.tmp`;
|
||||
await writeFile(temporary, snapshot, { encoding: 'utf8', mode: 0o600 });
|
||||
await rename(temporary, this.#path);
|
||||
});
|
||||
this.#writeQueue = operation.then(() => undefined, () => undefined);
|
||||
await operation;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue