Internalize all IM channel implementations

This commit is contained in:
xmanrui 2026-08-15 15:40:53 +08:00
parent 8996476693
commit bd469f58f8
95 changed files with 25012 additions and 100 deletions

View file

@ -0,0 +1,182 @@
import { createHash } from 'node:crypto';
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
import { normalizeWeixinApiBaseUrl } from './weixin-api.mjs';
const EMPTY_DOCUMENT = Object.freeze({ version: 1, accounts: Object.freeze([]) });
function cleanString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function safeBotId(value) {
const id = cleanString(value);
return id && /^wx_[a-f0-9]{24}$/.test(id) ? id : null;
}
function safeTokenRef(value) {
const ref = cleanString(value);
return ref && /^DSH_WEIXIN_BOT_TOKEN_[A-F0-9]{24}$/.test(ref) ? ref : null;
}
export function deriveWeixinBotIdentity(accountId) {
const raw = cleanString(accountId);
if (!raw) throw new TypeError('accountId is required');
const digest = createHash('sha256').update(raw).digest('hex').slice(0, 24);
return {
botId: `wx_${digest}`,
tokenRef: `DSH_WEIXIN_BOT_TOKEN_${digest.toUpperCase()}`,
};
}
export function maskWeixinAccountId(accountId) {
const value = cleanString(accountId) ?? '';
if (value.length <= 10) return value ? `${value.slice(0, 3)}•••` : '微信机器人';
return `${value.slice(0, 6)}••••${value.slice(-4)}`;
}
function normalizeAccount(value) {
if (!value || typeof value !== 'object') return null;
const accountId = cleanString(value.accountId);
const ownerUserId = cleanString(value.ownerUserId);
const botId = safeBotId(value.botId);
const tokenRef = safeTokenRef(value.tokenRef);
if (!accountId || !ownerUserId || !botId || !tokenRef) return null;
const derived = deriveWeixinBotIdentity(accountId);
if (derived.botId !== botId || derived.tokenRef !== tokenRef) return null;
let baseUrl;
try {
baseUrl = normalizeWeixinApiBaseUrl(value.baseUrl);
} catch {
return null;
}
return Object.freeze({
botId,
accountId,
tokenRef,
ownerUserId,
baseUrl,
createdAt: cleanString(value.createdAt) ?? new Date().toISOString(),
connectedAt: cleanString(value.connectedAt),
});
}
function normalizeDocument(value) {
if (!value || value.version !== 1 || !Array.isArray(value.accounts)) return null;
const accounts = value.accounts.map(normalizeAccount);
if (accounts.some((account) => account === null)) return null;
const ids = new Set();
const accountIds = new Set();
const refs = new Set();
for (const account of accounts) {
if (ids.has(account.botId) || accountIds.has(account.accountId) || refs.has(account.tokenRef)) {
return null;
}
ids.add(account.botId);
accountIds.add(account.accountId);
refs.add(account.tokenRef);
}
return Object.freeze({ version: 1, accounts: Object.freeze(accounts) });
}
export class WeixinConfigStore {
#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-weixin config contains invalid account data');
this.#value = normalized;
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
this.#value = EMPTY_DOCUMENT;
}
return this;
}
list() {
return structuredClone(this.#value.accounts);
}
get(botId) {
const account = this.#value.accounts.find((candidate) => candidate.botId === botId);
return account ? structuredClone(account) : null;
}
getByAccountId(accountId) {
const account = this.#value.accounts.find((candidate) => candidate.accountId === accountId);
return account ? structuredClone(account) : null;
}
async save(value) {
const normalized = normalizeAccount(value);
if (!normalized) throw new Error('Refusing to persist incomplete dsh-weixin account data');
return this.#mutate((accounts) => {
const accountCollision = accounts.find(
(account) => account.accountId === normalized.accountId && account.botId !== normalized.botId,
);
const refCollision = accounts.find(
(account) => account.tokenRef === normalized.tokenRef && account.botId !== normalized.botId,
);
if (accountCollision || refCollision) throw new Error('Duplicate Weixin account identity');
const index = accounts.findIndex((account) => account.botId === normalized.botId);
if (index === -1) accounts.push(normalized);
else accounts[index] = normalized;
return structuredClone(normalized);
});
}
async remove(botId) {
if (!safeBotId(botId)) throw new TypeError('Invalid Weixin bot id');
return this.#mutate((accounts) => {
const index = accounts.findIndex((account) => account.botId === botId);
if (index === -1) return null;
const [removed] = accounts.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 accounts = [...this.#value.accounts];
result = mutator(accounts);
const document = Object.freeze({ version: 1, accounts: Object.freeze(accounts) });
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);
}
}

View file

@ -0,0 +1,259 @@
import { spawn } from 'node:child_process';
import { randomUUID } from 'node:crypto';
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function assistantMessageText(event) {
return (event?.data?.message?.content ?? [])
.filter((part) => part.type === 'text' && typeof part.text === 'string')
.map((part) => part.text)
.join('\n')
.trim();
}
export class HarnessReplyTracker {
#promptRpcId;
#lastSeq;
#openTurn = null;
#targetTurn = null;
#stepText = new Map();
#latestText = '';
#finished = false;
#reason = null;
constructor({ promptRpcId, afterSeq = -1 }) {
this.#promptRpcId = promptRpcId;
this.#lastSeq = afterSeq;
}
get finished() {
return this.#finished;
}
get answer() {
return this.#latestText.trim();
}
get reason() {
return this.#reason;
}
consume(entries) {
let update = null;
const ordered = [...entries]
.map((entry) => entry?.event ?? entry)
.filter(Boolean)
.sort((left, right) => (left.seq ?? -1) - (right.seq ?? -1));
for (const event of ordered) {
const seq = event.seq ?? -1;
if (seq <= this.#lastSeq) continue;
this.#lastSeq = seq;
if (event.type === 'turn/start') this.#openTurn = event.data?.turn ?? null;
if (event.type === 'user/message' && event.data?.source?.rpcId === this.#promptRpcId) {
this.#targetTurn = this.#openTurn;
continue;
}
if (this.#targetTurn === null) continue;
if (event.type === 'turn/end') {
if (event.data?.turn !== this.#targetTurn) continue;
this.#finished = true;
this.#reason = event.data?.reason ?? null;
this.#openTurn = null;
continue;
}
if (event.data?.turn !== this.#targetTurn) continue;
if (event.type === 'assistant/chunk' && event.data?.chunk?.type === 'text-delta') {
const step = event.data?.step ?? 0;
const index = event.data.chunk.index ?? 0;
const key = `${step}:${index}`;
this.#stepText.set(key, (this.#stepText.get(key) ?? '') + event.data.chunk.text);
const prefix = `${step}:`;
const text = [...this.#stepText.entries()]
.filter(([partKey]) => partKey.startsWith(prefix))
.sort(([left], [right]) => Number(left.split(':')[1]) - Number(right.split(':')[1]))
.map(([, part]) => part)
.join('\n')
.trim();
if (text && text !== this.#latestText) {
this.#latestText = text;
update = { type: 'text', text };
}
continue;
}
if (event.type === 'assistant/message') {
const text = assistantMessageText(event);
if (text && text !== this.#latestText) {
this.#latestText = text;
update = { type: 'text', text };
}
continue;
}
if (event.type === 'tool/call') {
update = { type: 'tool', name: event.data?.name ?? '工具' };
} else if (event.type === 'tool/result') {
update = { type: 'status', text: '正在整理结果…' };
}
}
return update;
}
}
export class HarnessRpcError extends Error {
constructor(method, error) {
super(`${method}: ${error?.message ?? 'unknown Harness RPC error'}`);
this.name = 'HarnessRpcError';
this.method = method;
this.code = error?.code ?? 'internal';
this.details = error?.details ?? {};
}
}
export class HarnessClient {
#baseUrl;
#workspace;
#agentPreset;
#autostart;
#dshBin;
#managedProcess = null;
constructor({ baseUrl, workspace, agentPreset = 'standard', autostart = false, dshBin = 'dsh' }) {
this.#baseUrl = new URL(baseUrl);
this.#workspace = workspace;
this.#agentPreset = agentPreset;
this.#autostart = autostart;
this.#dshBin = dshBin;
}
async rpc(method, payload = {}, timeoutMs = 30_000, options = {}) {
const rpcId = options.rpcId ?? `weixin-${randomUUID()}`;
const response = await fetch(new URL(`/api/${method}`, this.#baseUrl), {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ type: 'client-request', rpcId, method, payload }),
signal: AbortSignal.timeout(timeoutMs),
});
if (!response.ok) throw new Error(`Harness transport ${method} failed: HTTP ${response.status}`);
const body = await response.json();
if (body?.type !== 'server-response' || body?.rpcId !== rpcId) {
throw new Error(`Harness returned an invalid response for ${method}`);
}
if (!body.result?.ok) throw new HarnessRpcError(method, body.result?.error);
return body.result.value;
}
async health() {
await this.rpc('host.describe', {}, 5_000);
return true;
}
async ensureRunning() {
try {
return await this.health();
} catch (firstError) {
if (!this.#autostart) throw firstError;
}
if (!this.#managedProcess || this.#managedProcess.exitCode !== null) {
const port = this.#baseUrl.port || (this.#baseUrl.protocol === 'https:' ? '443' : '80');
this.#managedProcess = spawn(this.#dshBin, [
'web', '--host', this.#baseUrl.hostname, '--port', port,
], {
cwd: this.#workspace,
env: process.env,
stdio: ['ignore', 'inherit', 'inherit'],
});
this.#managedProcess.on('error', (error) => {
console.error('[dsh-weixin] failed to start Harness:', error.message);
});
}
const deadline = Date.now() + 60_000;
let lastError;
while (Date.now() < deadline) {
await sleep(1_000);
try {
return await this.health();
} catch (error) {
lastError = error;
}
}
throw new Error(`Harness did not become ready: ${lastError?.message ?? 'timeout'}`);
}
async workspaceId() {
const { items } = await this.rpc('workspace.list', {});
const existing = items.find((item) => item.path === this.#workspace);
if (existing) return existing.workspaceId;
const created = await this.rpc('workspace.create', { path: this.#workspace });
return created.workspace.workspaceId;
}
async createSession() {
await this.ensureRunning();
const workspaceId = await this.workspaceId();
const created = await this.rpc('session.create', {
workspaceId,
agentPreset: this.#agentPreset,
});
return created.sessionId;
}
async sessionExists(sessionId) {
try {
await this.rpc('session.history', { sessionId, maxMessages: 1 });
return true;
} catch (error) {
if (error instanceof HarnessRpcError && error.code === 'session-not-found') return false;
throw error;
}
}
async ask(sessionId, text, options = {}) {
if (typeof options === 'number') options = { timeoutMs: options };
const timeoutMs = options.timeoutMs ?? 600_000;
const onUpdate = typeof options.onUpdate === 'function' ? options.onUpdate : null;
await this.ensureRunning();
const before = await this.rpc('session.history', { sessionId, maxMessages: 1 });
const baselineSeq = Math.max(-1, ...(before.events ?? []).map(({ event }) => event.seq ?? -1));
const promptRpcId = `weixin-${randomUUID()}`;
const tracker = new HarnessReplyTracker({ promptRpcId, afterSeq: baselineSeq });
await this.rpc('session.prompt', {
sessionId,
mode: 'queue',
content: [{ type: 'text', text }],
clientTimeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
}, 30_000, { rpcId: promptRpcId });
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
await sleep(300);
const history = await this.rpc('session.history', { sessionId, maxMessages: 50 });
const update = tracker.consume(history.events ?? []);
if (update && onUpdate) {
try {
await onUpdate(update);
} catch (error) {
console.warn('[dsh-weixin] ignored a progress update failure:', error.message);
}
}
if (!tracker.finished) continue;
if (tracker.answer) return tracker.answer;
throw new Error(
`Harness turn ended without a text reply${tracker.reason ? ` (${JSON.stringify(tracker.reason)})` : ''}`,
);
}
throw new Error(`Harness reply timed out after ${Math.round(timeoutMs / 1_000)} seconds`);
}
stopManagedProcess() {
if (this.#managedProcess?.exitCode === null) this.#managedProcess.kill('SIGTERM');
}
}

View file

@ -0,0 +1,112 @@
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
const EMPTY_STATE = Object.freeze({
version: 1,
sessions: {},
seenMessageIds: [],
getUpdatesBuf: '',
});
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)
: [],
getUpdatesBuf: typeof value.getUpdatesBuf === 'string' ? value.getUpdatesBuf : '',
};
}
export class WeixinStateStore {
#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();
}
getUpdatesBuf() {
return this.#state.getUpdatesBuf;
}
async setGetUpdatesBuf(value) {
if (typeof value !== 'string' || value === this.#state.getUpdatesBuf) return;
this.#state.getUpdatesBuf = value;
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;
}
}

View file

@ -0,0 +1,319 @@
import { randomBytes, randomUUID } from 'node:crypto';
export const WEIXIN_QR_BASE_URL = 'https://ilinkai.weixin.qq.com/';
export const WEIXIN_PROTOCOL_VERSION = '2.4.6';
export const DEFAULT_BOT_TYPE = '3';
const ILINK_APP_ID = 'bot';
const ILINK_CLIENT_VERSION = (2 << 16) | (4 << 8) | 6;
const DEFAULT_TIMEOUT_MS = 15_000;
const DEFAULT_LONG_POLL_TIMEOUT_MS = 35_000;
const LOGIN_STATUSES = new Set([
'wait',
'scaned',
'confirmed',
'expired',
'scaned_but_redirect',
'need_verifycode',
'verify_code_blocked',
'binded_redirect',
]);
export class WeixinApiError extends Error {
constructor(code, message, options = {}) {
super(message, options);
this.name = 'WeixinApiError';
this.code = code;
this.status = options.status;
}
}
function nonEmptyString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function isWeixinHost(hostname) {
const normalized = hostname.toLowerCase().replace(/\.$/, '');
return normalized === 'weixin.qq.com' || normalized.endsWith('.weixin.qq.com');
}
export function normalizeWeixinApiBaseUrl(value) {
let url;
try {
url = new URL(value);
} catch {
throw new WeixinApiError('invalid-base-url', '微信服务返回了无效的连接地址。');
}
if (url.protocol !== 'https:' || !isWeixinHost(url.hostname)
|| (url.port !== '' && url.port !== '443')) {
throw new WeixinApiError('untrusted-base-url', '微信服务返回了不受信任的连接地址。');
}
url.username = '';
url.password = '';
url.search = '';
url.hash = '';
if (!url.pathname.endsWith('/')) url.pathname += '/';
return url.toString();
}
export function normalizeWeixinQrUrl(value) {
const text = nonEmptyString(value);
if (!text) throw new WeixinApiError('invalid-qr', '微信服务没有返回扫码地址。');
let url;
try {
url = new URL(text);
} catch {
throw new WeixinApiError('invalid-qr', '微信服务返回了无效的扫码地址。');
}
if (url.protocol !== 'https:' || !isWeixinHost(url.hostname)) {
throw new WeixinApiError('untrusted-qr', '微信服务返回了不受信任的扫码地址。');
}
return url.toString();
}
function commonHeaders() {
return {
'iLink-App-Id': ILINK_APP_ID,
'iLink-App-ClientVersion': String(ILINK_CLIENT_VERSION),
};
}
function authenticatedHeaders(token) {
const headers = {
...commonHeaders(),
'content-type': 'application/json',
AuthorizationType: 'ilink_bot_token',
'X-WECHAT-UIN': Buffer.from(String(randomBytes(4).readUInt32BE(0)), 'utf8').toString('base64'),
};
if (nonEmptyString(token)) headers.Authorization = `Bearer ${token.trim()}`;
return headers;
}
function baseInfo() {
return {
channel_version: WEIXIN_PROTOCOL_VERSION,
bot_agent: 'DeepSeekHarness/0.1.0',
};
}
function abortError(signal) {
if (signal?.reason instanceof Error) return signal.reason;
return new DOMException('The operation was aborted', 'AbortError');
}
async function requestJson(fetchImpl, {
method,
baseUrl,
endpoint,
body,
token,
timeoutMs = DEFAULT_TIMEOUT_MS,
signal,
authenticated = true,
}) {
const trustedBase = normalizeWeixinApiBaseUrl(baseUrl);
const url = new URL(endpoint, trustedBase);
if (!isWeixinHost(url.hostname)) {
throw new WeixinApiError('untrusted-endpoint', '拒绝访问不受信任的微信服务地址。');
}
const controller = new AbortController();
let timedOut = false;
const onAbort = () => controller.abort(signal?.reason);
if (signal?.aborted) throw abortError(signal);
signal?.addEventListener('abort', onAbort, { once: true });
const timer = timeoutMs > 0 ? setTimeout(() => {
timedOut = true;
controller.abort();
}, timeoutMs) : null;
try {
const response = await fetchImpl(url, {
method,
headers: authenticated ? authenticatedHeaders(token) : commonHeaders(),
...(body === undefined ? {} : { body: JSON.stringify(body) }),
signal: controller.signal,
});
if (!response.ok) {
throw new WeixinApiError(
'http-error',
`微信服务请求失败(HTTP ${response.status})。`,
{ status: response.status },
);
}
try {
return await response.json();
} catch (error) {
throw new WeixinApiError('invalid-response', '微信服务返回了无法解析的响应。', { cause: error });
}
} catch (error) {
if (signal?.aborted) throw abortError(signal);
if (timedOut) {
throw new WeixinApiError('timeout', '微信服务请求超时。', { cause: error });
}
if (error instanceof WeixinApiError) throw error;
throw new WeixinApiError('network-error', '暂时无法访问微信服务。', { cause: error });
} finally {
if (timer) clearTimeout(timer);
signal?.removeEventListener('abort', onAbort);
}
}
function validateLoginResponse(value) {
if (!value || typeof value !== 'object' || !LOGIN_STATUSES.has(value.status)) {
throw new WeixinApiError('invalid-login-status', '微信服务返回了无法识别的扫码状态。');
}
return value;
}
export function createWeixinApi({ fetchImpl = fetch } = {}) {
if (typeof fetchImpl !== 'function') throw new TypeError('fetchImpl must be a function');
return Object.freeze({
async beginLogin({ localTokens = [], botType = DEFAULT_BOT_TYPE, signal } = {}) {
const tokens = [...new Set(localTokens.map(nonEmptyString).filter(Boolean))].slice(-10);
const response = await requestJson(fetchImpl, {
method: 'POST',
baseUrl: WEIXIN_QR_BASE_URL,
endpoint: `ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(botType)}`,
body: { local_token_list: tokens },
timeoutMs: 10_000,
signal,
});
const qrcode = nonEmptyString(response?.qrcode);
if (!qrcode) throw new WeixinApiError('invalid-qr', '微信服务没有返回二维码令牌。');
return {
qrcode,
qrcodeUrl: normalizeWeixinQrUrl(response.qrcode_img_content),
};
},
async pollLogin({ qrcode, baseUrl = WEIXIN_QR_BASE_URL, verifyCode, signal }) {
const qr = nonEmptyString(qrcode);
if (!qr) throw new TypeError('qrcode is required');
let endpoint = `ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(qr)}`;
if (nonEmptyString(verifyCode)) endpoint += `&verify_code=${encodeURIComponent(verifyCode.trim())}`;
const response = await requestJson(fetchImpl, {
method: 'GET',
baseUrl,
endpoint,
timeoutMs: DEFAULT_LONG_POLL_TIMEOUT_MS,
signal,
authenticated: false,
});
return validateLoginResponse(response);
},
async getUpdates({ baseUrl, token, getUpdatesBuf = '', timeoutMs, signal }) {
try {
return await requestJson(fetchImpl, {
method: 'POST',
baseUrl,
endpoint: 'ilink/bot/getupdates',
body: { get_updates_buf: getUpdatesBuf, base_info: baseInfo() },
token,
timeoutMs: timeoutMs ?? DEFAULT_LONG_POLL_TIMEOUT_MS,
signal,
});
} catch (error) {
if (error instanceof WeixinApiError && error.code === 'timeout') {
return { ret: 0, msgs: [], get_updates_buf: getUpdatesBuf };
}
throw error;
}
},
async sendText({ baseUrl, token, toUserId, text, contextToken, runId, signal }) {
const recipient = nonEmptyString(toUserId);
const content = nonEmptyString(text);
if (!recipient || !content) throw new TypeError('toUserId and text are required');
const response = await requestJson(fetchImpl, {
method: 'POST',
baseUrl,
endpoint: 'ilink/bot/sendmessage',
token,
signal,
body: {
msg: {
from_user_id: '',
to_user_id: recipient,
client_id: `dsh-weixin-${randomUUID()}`,
message_type: 2,
message_state: 2,
item_list: [{ type: 1, text_item: { text: content } }],
...(nonEmptyString(contextToken) ? { context_token: contextToken.trim() } : {}),
...(nonEmptyString(runId) ? { run_id: runId.trim() } : {}),
},
base_info: baseInfo(),
},
});
if (response?.ret !== undefined && response.ret !== 0) {
throw new WeixinApiError('send-rejected', '微信服务拒绝了回复消息。');
}
return true;
},
async notifyStart({ baseUrl, token, signal }) {
const response = await requestJson(fetchImpl, {
method: 'POST',
baseUrl,
endpoint: 'ilink/bot/msg/notifystart',
token,
signal,
timeoutMs: 10_000,
body: { base_info: baseInfo() },
});
if (response?.ret !== undefined && response.ret !== 0) {
throw new WeixinApiError('start-rejected', '微信账号连接启动失败。');
}
return response;
},
async notifyStop({ baseUrl, token, signal }) {
return requestJson(fetchImpl, {
method: 'POST',
baseUrl,
endpoint: 'ilink/bot/msg/notifystop',
token,
signal,
timeoutMs: 10_000,
body: { base_info: baseInfo() },
});
},
});
}
export function extractWeixinText(message) {
for (const item of message?.item_list ?? []) {
if (item?.type === 1 && typeof item.text_item?.text === 'string') {
const text = item.text_item.text.trim();
if (text) return text;
}
if (item?.type === 3 && typeof item.voice_item?.text === 'string') {
const text = item.voice_item.text.trim();
if (text) return text;
}
}
return null;
}
export function weixinMessageId(message) {
if (message?.message_id !== undefined && message.message_id !== null) {
return String(message.message_id);
}
return nonEmptyString(message?.client_id);
}
export function splitWeixinText(text, maxChars = 4_000) {
if (text.length <= maxChars) return [text];
const chunks = [];
let remaining = text;
while (remaining.length > maxChars) {
let splitAt = remaining.lastIndexOf('\n', maxChars);
if (splitAt < Math.floor(maxChars * 0.6)) splitAt = maxChars;
chunks.push(remaining.slice(0, splitAt));
remaining = remaining.slice(splitAt).replace(/^\n+/, '');
}
if (remaining) chunks.push(remaining);
return chunks;
}

View file

@ -0,0 +1,173 @@
import {
extractWeixinText,
splitWeixinText,
weixinMessageId,
} from './weixin-api.mjs';
const HELP_TEXT = [
'微信已连接 DeepSeek Harness。',
'',
'直接发送文字或带文字识别结果的语音即可继续当前会话。',
'/new 开启一个全新会话',
'/status 检查连接状态',
'/help 显示本帮助',
].join('\n');
function conversationKey(userId) {
return `p2p:${userId}`;
}
export function createWeixinBridgeStatus() {
return {
messagesReceived: 0,
messagesReplied: 0,
messagesRejected: 0,
lastMessageAt: null,
lastReplyAt: null,
lastRejectedAt: null,
lastError: null,
};
}
export class WeixinHarnessBridge {
#api;
#baseUrl;
#token;
#ownerUserId;
#harness;
#state;
#status;
#logger;
#replyTimeoutMs;
#maxMessageChars;
#queues = new Map();
constructor({
api,
baseUrl,
token,
ownerUserId,
harness,
state,
status = createWeixinBridgeStatus(),
logger = console,
replyTimeoutMs = 600_000,
maxMessageChars = 4_000,
}) {
if (!api || typeof api.sendText !== 'function') throw new TypeError('Weixin API is required');
if (!baseUrl || !token || !ownerUserId) throw new TypeError('Weixin account credentials are required');
if (!harness || !state) throw new TypeError('Harness client and state store are required');
this.#api = api;
this.#baseUrl = baseUrl;
this.#token = token;
this.#ownerUserId = ownerUserId;
this.#harness = harness;
this.#state = state;
this.#status = status;
this.#logger = logger;
this.#replyTimeoutMs = replyTimeoutMs;
this.#maxMessageChars = maxMessageChars;
}
get status() {
return structuredClone(this.#status);
}
accept(message) {
const sender = typeof message?.from_user_id === 'string' ? message.from_user_id : '';
const previous = this.#queues.get(sender) ?? Promise.resolve();
const current = previous
.catch(() => undefined)
.then(() => this.#process(message))
.finally(() => {
if (this.#queues.get(sender) === current) this.#queues.delete(sender);
});
this.#queues.set(sender, current);
return current;
}
async waitForIdle() {
await Promise.allSettled([...this.#queues.values()]);
}
async #process(message) {
if (message?.message_type === 2) return;
const messageId = weixinMessageId(message);
const sender = typeof message?.from_user_id === 'string' ? message.from_user_id : '';
if (!messageId || !sender) return;
if (this.#state.hasSeen(messageId)) return;
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
if (sender !== this.#ownerUserId) {
this.#status.messagesRejected += 1;
this.#status.lastRejectedAt = new Date().toISOString();
return;
}
const contextToken = typeof message.context_token === 'string' ? message.context_token : undefined;
const runId = typeof message.run_id === 'string' ? message.run_id : undefined;
const text = extractWeixinText(message);
try {
if (!text) {
await this.#send(sender, '目前仅支持文字消息,以及微信已转成文字的语音消息。', contextToken, runId);
await this.#state.markSeen(messageId);
return;
}
const command = text.trim().toLowerCase();
if (command === '/help') {
await this.#send(sender, HELP_TEXT, contextToken, runId);
await this.#state.markSeen(messageId);
return;
}
if (command === '/status') {
await this.#harness.ensureRunning();
await this.#send(sender, '微信与 DeepSeek Harness 连接正常。', contextToken, runId);
await this.#state.markSeen(messageId);
return;
}
if (command === '/new') {
await this.#state.clearSession(conversationKey(sender));
await this.#send(sender, '已开启新会话。请发送你的问题。', contextToken, runId);
await this.#state.markSeen(messageId);
return;
}
const key = conversationKey(sender);
let sessionId = this.#state.sessionFor(key);
if (!sessionId || !(await this.#harness.sessionExists(sessionId))) {
sessionId = await this.#harness.createSession();
await this.#state.setSession(key, sessionId);
}
const answer = await this.#harness.ask(sessionId, text, { timeoutMs: this.#replyTimeoutMs });
await this.#send(sender, answer, contextToken, runId);
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-weixin] failed to process an inbound message:', error);
try {
await this.#send(sender, '消息处理失败,请稍后重试。', contextToken, runId);
await this.#state.markSeen(messageId);
} catch (sendError) {
this.#logger.error?.('[dsh-weixin] failed to send the safe error reply:', sendError);
}
}
}
async #send(toUserId, text, contextToken, runId) {
for (const chunk of splitWeixinText(text, this.#maxMessageChars)) {
await this.#api.sendText({
baseUrl: this.#baseUrl,
token: this.#token,
toUserId,
text: chunk,
contextToken,
runId,
});
}
}
}

View file

@ -0,0 +1,545 @@
import { randomUUID } from 'node:crypto';
import {
normalizeWeixinApiBaseUrl,
WEIXIN_QR_BASE_URL,
WeixinApiError,
} from './weixin-api.mjs';
import { deriveWeixinBotIdentity, maskWeixinAccountId } from './config-store.mjs';
const ACTIVE_ATTEMPT_STATES = new Set([
'starting',
'pending',
'scanned',
'needs_verification',
'connecting',
]);
const TERMINAL_ATTEMPT_STATES = new Set(['connected', 'expired', 'failed', 'cancelled']);
const QR_TTL_MS = 5 * 60_000;
function cleanString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function abortError() {
return new DOMException('Provisioning was cancelled', 'AbortError');
}
function apiBaseFromServer(value, fallback) {
const raw = cleanString(value);
if (!raw) return normalizeWeixinApiBaseUrl(fallback);
return normalizeWeixinApiBaseUrl(raw.includes('://') ? raw : `https://${raw}`);
}
function publicAttempt(record) {
if (!record) return null;
return {
attemptId: record.id,
status: record.state,
...(record.verificationUrl ? { verificationUrl: record.verificationUrl } : {}),
...(record.expiresAt ? { expiresAt: record.expiresAt } : {}),
pollIntervalMs: 1_000,
...(record.state === 'needs_verification' ? { verificationRequired: true } : {}),
...(record.botId ? { botId: record.botId } : {}),
...(record.alreadyConnected ? { alreadyConnected: true } : {}),
...(record.error ? { error: structuredClone(record.error) } : {}),
};
}
function safeAccountError(code, message) {
return Object.freeze({ code, message });
}
export class WeixinController {
#api;
#credentials;
#configStore;
#createRuntime;
#deleteState;
#logger;
#runtimes = new Map();
#errors = new Map();
#attempts = new Map();
#activeAttemptId = null;
#transitions = new Map();
#revision = 0;
#closed = false;
constructor({
api,
credentials,
configStore,
createRuntime,
deleteState = async () => {},
logger = console,
}) {
if (!api || typeof api.beginLogin !== 'function' || typeof api.pollLogin !== 'function') {
throw new TypeError('WeixinController requires a Weixin API client');
}
if (!credentials
|| typeof credentials.resolve !== 'function'
|| typeof credentials.set !== 'function'
|| typeof credentials.unset !== 'function') {
throw new TypeError('WeixinController requires the DSH credential provider');
}
if (!configStore
|| typeof configStore.list !== 'function'
|| typeof configStore.save !== 'function'
|| typeof configStore.remove !== 'function') {
throw new TypeError('WeixinController requires a config store');
}
if (typeof createRuntime !== 'function') throw new TypeError('createRuntime is required');
this.#api = api;
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()) {
const current = this.#runtimes.get(config.botId);
if (current?.status?.ready === true) continue;
await this.#withBotTransition(config.botId, async () => {
const latest = this.#configStore.get(config.botId);
if (!latest || this.#closed) return;
try {
const token = await this.#resolveToken(latest.tokenRef);
if (!token) {
this.#errors.set(
latest.botId,
safeAccountError('missing-token', '登录凭据缺失,请移除账号后重新扫码。'),
);
return;
}
await this.#startRuntime(latest, token);
this.#errors.delete(latest.botId);
} catch (error) {
this.#errors.set(
latest.botId,
safeAccountError('connection-failed', '微信连接未就绪,插件会自动重试。'),
);
this.#logger.warn?.(`[dsh-weixin] account ${latest.botId} failed to initialize:`, error);
} finally {
this.#touch();
}
});
}
return this.status();
}
async startProvisioning() {
if (this.#closed) throw new Error('dsh-weixin controller is closed');
if (this.#activeAttemptId) await this.cancelProvisioning(this.#activeAttemptId);
const record = {
id: randomUUID(),
state: 'starting',
createdAt: Date.now(),
expiresAt: Date.now() + QR_TTL_MS,
controller: new AbortController(),
pendingVerifyCode: null,
verifyResolve: null,
currentBaseUrl: WEIXIN_QR_BASE_URL,
error: null,
botId: null,
task: null,
};
this.#attempts.set(record.id, record);
this.#activeAttemptId = record.id;
this.#touch();
try {
const localTokens = (await Promise.all(
this.#configStore.list().slice(-10).map(async (config) => this.#resolveToken(config.tokenRef)),
)).filter(Boolean);
const login = await this.#api.beginLogin({
localTokens,
signal: record.controller.signal,
});
this.#assertAttemptActive(record);
record.qrcode = login.qrcode;
record.verificationUrl = login.qrcodeUrl;
record.state = 'pending';
record.expiresAt = Date.now() + QR_TTL_MS;
this.#touch();
record.task = this.#runProvisioning(record);
return publicAttempt(record);
} catch (error) {
if (record.controller.signal.aborted) {
record.state = 'cancelled';
record.error = safeAccountError('cancelled', '扫码绑定已取消。');
} else {
record.state = 'failed';
record.error = safeAccountError(
error instanceof WeixinApiError ? error.code : 'qr-start-failed',
error instanceof WeixinApiError ? error.message : '无法生成微信二维码,请稍后重试。',
);
}
if (this.#activeAttemptId === record.id) this.#activeAttemptId = null;
this.#touch();
throw error;
}
}
registrationStatus(attemptId) {
return publicAttempt(this.#attempts.get(attemptId));
}
async submitVerification(attemptId, verifyCode) {
const record = this.#attempts.get(attemptId);
if (!record || record.state !== 'needs_verification') {
throw new Error('The provisioning attempt is not waiting for a verification code');
}
const code = cleanString(verifyCode);
if (!code || !/^\d{4,8}$/.test(code)) {
throw new TypeError('Verification code must contain 4 to 8 digits');
}
record.pendingVerifyCode = code;
record.state = 'scanned';
record.verifyResolve?.();
record.verifyResolve = null;
this.#touch();
return publicAttempt(record);
}
async cancelProvisioning(attemptId) {
const record = this.#attempts.get(attemptId);
if (!record) return null;
if (!TERMINAL_ATTEMPT_STATES.has(record.state)) {
record.controller.abort();
record.verifyResolve?.();
record.verifyResolve = null;
await record.task?.catch(() => undefined);
if (!TERMINAL_ATTEMPT_STATES.has(record.state)) record.state = 'cancelled';
record.error ??= safeAccountError('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 Weixin account');
await this.#withBotTransition(botId, async () => {
const token = await this.#resolveToken(config.tokenRef);
if (!token) throw new Error('The Weixin token is missing');
try {
await this.#startRuntime(config, token);
this.#errors.delete(botId);
} catch (error) {
this.#errors.set(botId, safeAccountError('connection-failed', '微信连接仍未就绪,请稍后重试。'));
throw error;
} finally {
this.#touch();
}
});
return this.status();
}
async deleteBot(botId) {
const config = this.#configStore.get(botId);
if (!config) throw new Error('Unknown Weixin account');
await this.#withBotTransition(botId, async () => {
const previousToken = await this.#credentials.resolve(config.tokenRef).catch(() => undefined);
await this.#stopRuntime(botId);
try {
await this.#credentials.unset(config.tokenRef);
await this.#configStore.remove(botId);
} catch (error) {
if (previousToken?.value) {
await this.#credentials.set(config.tokenRef, previousToken.value).catch(() => undefined);
await this.#startRuntime(config, previousToken.value).catch(() => undefined);
}
throw new Error('Unable to remove the Weixin account safely.', { cause: error });
}
try {
await this.#deleteState({ botId, config });
} catch (error) {
this.#logger.warn?.(`[dsh-weixin] account ${botId} state cleanup failed:`, error);
}
this.#errors.delete(botId);
this.#touch();
});
return this.status();
}
status() {
const accounts = this.#configStore.list().map((config) => {
const runtimeStatus = this.#runtimes.get(config.botId)?.status ?? null;
const connected = runtimeStatus?.ready === true
&& runtimeStatus.weixinConnectionState === 'connected'
&& runtimeStatus.harnessReachable === true;
const state = connected
? 'connected'
: runtimeStatus?.weixinConnectionState === 'connecting'
? 'connecting'
: this.#errors.has(config.botId) || runtimeStatus?.weixinConnectionState === 'failed'
? 'error'
: 'offline';
const error = this.#errors.get(config.botId) ?? (state === 'error'
? safeAccountError('connection-failed', '微信连接未就绪,插件会自动重试。')
: null);
return {
botId: config.botId,
state,
connected,
configured: true,
bot: {
name: '微信机器人',
accountIdMasked: maskWeixinAccountId(config.accountId),
},
health: {
status: connected ? 'healthy' : state === 'error' ? 'error' : 'offline',
summary: connected
? '微信消息长轮询运行正常'
: state === 'error'
? '微信连接未就绪,插件会自动重试'
: '微信连接当前离线',
lastCheckedAt: runtimeStatus?.lastCheckedAt ?? null,
},
stats: {
messagesReceived: runtimeStatus?.messagesReceived ?? 0,
messagesReplied: runtimeStatus?.messagesReplied ?? 0,
},
error: error ? structuredClone(error) : null,
};
});
const connectedCount = accounts.filter((account) => account.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'
: accounts.length === 0
? 'disconnected'
: connectedCount === accounts.length
? 'connected'
: connectedCount > 0
? 'degraded'
: 'offline',
bots: accounts,
totals: { configured: accounts.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 #runProvisioning(record) {
try {
while (!record.controller.signal.aborted && Date.now() < record.expiresAt) {
if (record.state === 'needs_verification' && !record.pendingVerifyCode) {
await new Promise((resolve) => {
record.verifyResolve = resolve;
if (record.controller.signal.aborted) resolve();
});
record.verifyResolve = null;
this.#assertAttemptActive(record);
}
const response = await this.#api.pollLogin({
qrcode: record.qrcode,
baseUrl: record.currentBaseUrl,
verifyCode: record.pendingVerifyCode,
signal: record.controller.signal,
});
this.#assertAttemptActive(record);
if (response.status === 'wait') {
record.state = 'pending';
} else if (response.status === 'scaned') {
record.pendingVerifyCode = null;
record.state = 'scanned';
} else if (response.status === 'need_verifycode') {
record.pendingVerifyCode = null;
record.state = 'needs_verification';
} else if (response.status === 'verify_code_blocked') {
record.state = 'failed';
record.error = safeAccountError('verification-blocked', '配对码多次错误,请重新生成二维码。');
break;
} else if (response.status === 'expired') {
record.state = 'expired';
record.error = safeAccountError('expired', '二维码已过期,请重新生成。');
break;
} else if (response.status === 'scaned_but_redirect') {
record.currentBaseUrl = apiBaseFromServer(response.redirect_host, record.currentBaseUrl);
record.state = 'scanned';
} else if (response.status === 'binded_redirect') {
const existing = this.#configStore.list().find(
(config) => this.#runtimes.get(config.botId)?.status?.ready === true,
) ?? this.#configStore.list()[0];
if (!existing) {
record.state = 'failed';
record.error = safeAccountError('already-bound', '该微信账号已绑定,但本机没有可恢复的凭据。');
} else {
record.state = 'connected';
record.botId = existing.botId;
record.alreadyConnected = true;
}
break;
} else if (response.status === 'confirmed') {
const token = cleanString(response.bot_token);
const accountId = cleanString(response.ilink_bot_id);
const ownerUserId = cleanString(response.ilink_user_id);
if (!token || !accountId || !ownerUserId) {
throw new WeixinApiError('incomplete-login', '微信授权成功,但返回的账号凭据不完整。');
}
record.state = 'connecting';
this.#touch();
const baseUrl = apiBaseFromServer(response.baseurl, record.currentBaseUrl);
record.botId = await this.#activateAccount(record, {
token,
accountId,
ownerUserId,
baseUrl,
});
record.state = 'connected';
record.error = null;
break;
}
this.#touch();
}
if (!record.controller.signal.aborted && Date.now() >= record.expiresAt
&& !TERMINAL_ATTEMPT_STATES.has(record.state)) {
record.state = 'expired';
record.error = safeAccountError('expired', '二维码已过期,请重新生成。');
}
} catch (error) {
if (record.controller.signal.aborted || error?.name === 'AbortError') {
record.state = 'cancelled';
record.error = safeAccountError('cancelled', '扫码绑定已取消。');
} else {
record.state = 'failed';
record.error = safeAccountError(
error instanceof WeixinApiError ? error.code : 'activation-failed',
error instanceof WeixinApiError
? error.message
: '微信已授权,但无法保存凭据或启动消息连接。',
);
this.#logger.error?.('[dsh-weixin] provisioning failed:', error);
}
} finally {
record.pendingVerifyCode = null;
record.verifyResolve?.();
record.verifyResolve = null;
if (this.#activeAttemptId === record.id) this.#activeAttemptId = null;
this.#touch();
this.#pruneAttempts();
}
}
async #activateAccount(record, { token, accountId, ownerUserId, baseUrl }) {
const identity = deriveWeixinBotIdentity(accountId);
const previousConfig = this.#configStore.getByAccountId(accountId);
const config = {
botId: identity.botId,
accountId,
tokenRef: identity.tokenRef,
ownerUserId,
baseUrl,
createdAt: previousConfig?.createdAt ?? new Date().toISOString(),
connectedAt: new Date().toISOString(),
};
const previousToken = await this.#credentials.resolve(identity.tokenRef).catch(() => undefined);
return this.#withBotTransition(identity.botId, async () => {
await this.#credentials.set(identity.tokenRef, token);
try {
this.#assertAttemptActive(record);
await this.#configStore.save(config);
this.#assertAttemptActive(record);
await this.#startRuntime(config, token);
this.#assertAttemptActive(record);
this.#errors.delete(identity.botId);
this.#touch();
return identity.botId;
} catch (error) {
await this.#stopRuntime(identity.botId);
if (previousConfig) await this.#configStore.save(previousConfig).catch(() => undefined);
else if (this.#configStore.get(identity.botId)) {
await this.#configStore.remove(identity.botId).catch(() => undefined);
}
await this.#restoreCredential(identity.tokenRef, previousToken);
if (previousConfig && previousToken?.value) {
await this.#startRuntime(previousConfig, previousToken.value).catch(() => undefined);
}
throw error;
}
});
}
async #startRuntime(config, token) {
await this.#stopRuntime(config.botId);
const runtime = await this.#createRuntime({ botId: config.botId, config, token });
if (!runtime || typeof runtime.start !== 'function' || typeof runtime.stop !== 'function') {
throw new TypeError('createRuntime returned an invalid Weixin runtime');
}
try {
await runtime.start();
this.#runtimes.set(config.botId, runtime);
} catch (error) {
await runtime.stop().catch(() => undefined);
throw error;
}
}
async #stopRuntime(botId) {
const runtime = this.#runtimes.get(botId);
this.#runtimes.delete(botId);
await runtime?.stop().catch((error) => {
this.#logger.warn?.(`[dsh-weixin] account ${botId} failed to stop cleanly:`, error);
});
}
async #resolveToken(ref) {
const result = await this.#credentials.resolve(ref).catch(() => undefined);
return cleanString(result?.value);
}
async #restoreCredential(ref, previous) {
try {
if (previous?.value) await this.#credentials.set(ref, previous.value);
else await this.#credentials.unset(ref);
} catch (error) {
this.#logger.error?.(`[dsh-weixin] failed to restore credential ${ref}:`, error);
}
}
#assertAttemptActive(record) {
if (record.controller.signal.aborted || this.#activeAttemptId !== record.id) throw abortError();
}
#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;
}
#pruneAttempts() {
for (const [id, record] of this.#attempts) {
if (id !== this.#activeAttemptId && TERMINAL_ATTEMPT_STATES.has(record.state)
&& this.#attempts.size > 16) {
this.#attempts.delete(id);
}
}
}
#touch() {
this.#revision += 1;
}
}

View file

@ -0,0 +1,204 @@
import { WeixinApiError } from './weixin-api.mjs';
import { createWeixinBridgeStatus, WeixinHarnessBridge } from './weixin-bridge.mjs';
function delay(ms, signal) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
return;
}
const finish = () => {
signal?.removeEventListener('abort', onAbort);
resolve();
};
const timer = setTimeout(finish, ms);
const onAbort = () => {
clearTimeout(timer);
signal?.removeEventListener('abort', onAbort);
reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
};
signal?.addEventListener('abort', onAbort, { once: true });
});
}
export function createWeixinRuntimeStatus() {
return {
startedAt: null,
ready: false,
weixinConnectionState: 'idle',
harnessReachable: false,
lastCheckedAt: null,
lastError: null,
...createWeixinBridgeStatus(),
};
}
export class WeixinRuntime {
#api;
#config;
#token;
#harness;
#state;
#logger;
#replyTimeoutMs;
#maxMessageChars;
#status = createWeixinRuntimeStatus();
#bridge = null;
#abortController = null;
#monitor = null;
#starting = null;
constructor({
api,
config,
token,
harness,
state,
logger = console,
replyTimeoutMs = 600_000,
maxMessageChars = 4_000,
}) {
if (!api || !config || !token || !harness || !state) {
throw new TypeError('WeixinRuntime requires API, account, token, Harness, and state');
}
this.#api = api;
this.#config = config;
this.#token = token;
this.#harness = harness;
this.#state = state;
this.#logger = logger;
this.#replyTimeoutMs = replyTimeoutMs;
this.#maxMessageChars = maxMessageChars;
}
get status() {
return structuredClone(this.#status);
}
async start() {
if (this.#status.ready && this.#monitor) 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.weixinConnectionState = 'connecting';
this.#status.lastError = null;
try {
await this.#harness.ensureRunning();
this.#status.harnessReachable = true;
await this.#api.notifyStart({
baseUrl: this.#config.baseUrl,
token: this.#token,
});
this.#bridge = new WeixinHarnessBridge({
api: this.#api,
baseUrl: this.#config.baseUrl,
token: this.#token,
ownerUserId: this.#config.ownerUserId,
harness: this.#harness,
state: this.#state,
status: this.#status,
logger: this.#logger,
replyTimeoutMs: this.#replyTimeoutMs,
maxMessageChars: this.#maxMessageChars,
});
this.#abortController = new AbortController();
this.#status.ready = true;
this.#status.weixinConnectionState = 'connected';
this.#status.lastCheckedAt = Date.now();
const signal = this.#abortController.signal;
this.#monitor = this.#runMonitor(signal).catch((error) => {
if (signal.aborted) return;
this.#status.ready = false;
this.#status.weixinConnectionState = 'failed';
this.#status.lastError = error?.message ?? String(error);
this.#logger.error?.(`[dsh-weixin] account ${this.#config.botId} monitor stopped:`, error);
});
return this.status;
} catch (error) {
this.#status.ready = false;
this.#status.weixinConnectionState = 'failed';
this.#status.lastError = error?.message ?? String(error);
throw error;
}
}
async #runMonitor(signal) {
let consecutiveFailures = 0;
while (!signal.aborted) {
try {
const response = await this.#api.getUpdates({
baseUrl: this.#config.baseUrl,
token: this.#token,
getUpdatesBuf: this.#state.getUpdatesBuf(),
signal,
});
if (signal.aborted) return;
const rejected = (response?.ret !== undefined && response.ret !== 0)
|| (response?.errcode !== undefined && response.errcode !== 0);
if (rejected) {
const code = response.errcode ?? response.ret;
throw new WeixinApiError(
code === -14 ? 'stale-token' : 'updates-rejected',
code === -14 ? '微信登录凭据已失效,请移除账号后重新扫码。' : '微信消息同步请求被拒绝。',
);
}
consecutiveFailures = 0;
this.#status.ready = true;
this.#status.weixinConnectionState = 'connected';
this.#status.lastCheckedAt = Date.now();
this.#status.lastError = null;
for (const message of response?.msgs ?? []) {
await this.#bridge.accept(message);
}
if (typeof response?.get_updates_buf === 'string' && response.get_updates_buf) {
await this.#state.setGetUpdatesBuf(response.get_updates_buf);
}
} catch (error) {
if (signal.aborted) return;
consecutiveFailures += 1;
this.#status.lastError = error?.message ?? String(error);
this.#logger.warn?.(
`[dsh-weixin] account ${this.#config.botId} poll failed (${consecutiveFailures}/3):`,
error,
);
if (error instanceof WeixinApiError && error.code === 'stale-token') throw error;
if (consecutiveFailures >= 3) throw error;
await delay(Math.min(2_000 * (2 ** (consecutiveFailures - 1)), 10_000), signal);
}
}
}
async stop() {
const monitor = this.#monitor;
const bridge = this.#bridge;
const wasStarted = Boolean(this.#abortController || monitor || this.#status.ready);
this.#abortController?.abort();
this.#abortController = null;
this.#monitor = null;
await monitor?.catch(() => undefined);
await bridge?.waitForIdle();
this.#bridge = null;
if (wasStarted) {
try {
await this.#api.notifyStop({
baseUrl: this.#config.baseUrl,
token: this.#token,
signal: AbortSignal.timeout(10_000),
});
} catch (error) {
this.#logger.warn?.(`[dsh-weixin] account ${this.#config.botId} stop notification failed:`, error);
}
}
this.#status.ready = false;
this.#status.weixinConnectionState = 'idle';
return this.status;
}
}