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,282 @@
import { createHash, randomUUID } 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([]) });
const STORED_BOT_KEYS = new Set(['clientId', 'secretRef', 'approvedSenders']);
function cleanString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function digest(value) {
return createHash('sha256').update(value).digest('hex');
}
function safeBotId(value) {
const id = cleanString(value);
return id && /^dt_[a-f0-9]{24}$/.test(id) ? id : null;
}
function safeSecretRef(value) {
const ref = cleanString(value);
return ref && /^DSH_DINGTALK_BOT_SECRET_[A-F0-9]{24}$/.test(ref) ? ref : null;
}
function safeSenderKey(value) {
const key = cleanString(value);
return key && /^dt_sender_[a-f0-9]{32}$/.test(key) ? key : null;
}
function normalizeApprovedSender(value) {
const record = typeof value === 'string' ? { staffId: value } : value;
if (!record || typeof record !== 'object' || Array.isArray(record)) return null;
const senderKey = safeSenderKey(record.senderKey);
const staffId = cleanString(record.staffId);
if (!senderKey || !staffId) return null;
return Object.freeze({
senderKey,
staffId,
displayName: cleanString(record.displayName),
approvedAt: cleanString(record.approvedAt),
});
}
function normalizeApprovedSenders(value) {
if (!Array.isArray(value)) return null;
const senders = value.map(normalizeApprovedSender);
if (senders.some((sender) => sender === null)) return null;
const ids = new Set();
const keys = new Set();
for (const sender of senders) {
if (ids.has(sender.staffId) || keys.has(sender.senderKey)) return null;
ids.add(sender.staffId);
keys.add(sender.senderKey);
}
return Object.freeze(senders);
}
/**
* Derives stable non-secret identifiers for a DingTalk bot credential.
* @param {string} clientId DingTalk application client ID.
* @returns {{botId: string, secretRef: string}} Derived identifiers.
*/
export function deriveDingtalkBotIdentity(clientId) {
const value = cleanString(clientId);
if (!value) throw new TypeError('clientId is required');
const valueDigest = digest(value).slice(0, 24);
return Object.freeze({
botId: `dt_${valueDigest}`,
secretRef: `DSH_DINGTALK_BOT_SECRET_${valueDigest.toUpperCase()}`,
});
}
/**
* Creates a random browser-safe key for an approved DingTalk sender.
* @returns {string} Opaque sender key.
*/
export function deriveDingtalkSenderKey() {
return `dt_sender_${randomUUID().replaceAll('-', '')}`;
}
/**
* Redacts a DingTalk sender ID for display.
* @param {string} staffId DingTalk staff ID.
* @returns {string} Partially redacted identifier.
*/
export function maskDingtalkSenderId(staffId) {
const value = cleanString(staffId);
if (!value) return '钉钉用户';
return '身份已隐藏';
}
/**
* Redacts a DingTalk client ID for display.
* @param {string} clientId DingTalk application client ID.
* @returns {string} Partially redacted client ID.
*/
export function maskDingtalkClientId(clientId) {
const value = cleanString(clientId);
if (!value) return '钉钉机器人';
if (value.length <= 8) return `${value.slice(0, 2)}••••`;
return `${value.slice(0, 4)}••••${value.slice(-4)}`;
}
function normalizeBot(value, { stored = false } = {}) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
if ('clientSecret' in value || 'client_secret' in value || 'deviceCode' in value) return null;
if (stored && Object.keys(value).some((key) => !STORED_BOT_KEYS.has(key))) return null;
const clientId = cleanString(value.clientId);
const secretRef = safeSecretRef(value.secretRef);
const approvedSenders = normalizeApprovedSenders(value.approvedSenders ?? []);
if (!clientId || !secretRef || !approvedSenders) return null;
const identity = deriveDingtalkBotIdentity(clientId);
if (identity.secretRef !== secretRef) return null;
const suppliedBotId = value.botId === undefined ? identity.botId : safeBotId(value.botId);
if (suppliedBotId !== identity.botId) return null;
return Object.freeze({
botId: identity.botId,
clientId,
secretRef,
approvedSenders,
});
}
function normalizeDocument(value) {
if (!value || value.version !== 1 || !Array.isArray(value.bots)) return null;
const bots = value.bots.map((bot) => normalizeBot(bot, { stored: true }));
if (bots.some((bot) => bot === null)) return null;
const botIds = new Set();
const clientIds = new Set();
const secretRefs = new Set();
for (const bot of bots) {
if (botIds.has(bot.botId) || clientIds.has(bot.clientId) || secretRefs.has(bot.secretRef)) {
return null;
}
botIds.add(bot.botId);
clientIds.add(bot.clientId);
secretRefs.add(bot.secretRef);
}
return Object.freeze({ version: 1, bots: Object.freeze(bots) });
}
function storedDocument(document) {
return {
version: 1,
bots: document.bots.map((bot) => ({
clientId: bot.clientId,
secretRef: bot.secretRef,
approvedSenders: bot.approvedSenders.map((sender) => ({
senderKey: sender.senderKey,
staffId: sender.staffId,
displayName: sender.displayName,
approvedAt: sender.approvedAt,
})),
})),
};
}
/** Atomic non-secret DingTalk bot configuration store. */
export class DingtalkConfigStore {
#path;
#value = EMPTY_DOCUMENT;
#writeQueue = Promise.resolve();
/** @param {string} path Absolute or process-relative configuration file path. */
constructor(path) {
if (!cleanString(path)) throw new TypeError('config path is required');
this.#path = path;
}
/** @returns {Promise<DingtalkConfigStore>} Loaded store. */
async load() {
try {
const normalized = normalizeDocument(JSON.parse(await readFile(this.#path, 'utf8')));
if (!normalized) throw new Error('dsh-dingtalk config contains invalid bot data');
this.#value = normalized;
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
this.#value = EMPTY_DOCUMENT;
}
return this;
}
/** @returns {Array<object>} Cloned bot configurations with derived bot IDs. */
list() {
return structuredClone(this.#value.bots);
}
/** @param {string} botId Derived bot ID. @returns {object|null} Bot configuration. */
get(botId) {
const found = this.#value.bots.find((bot) => bot.botId === botId);
return found ? structuredClone(found) : null;
}
/** @param {string} clientId DingTalk client ID. @returns {object|null} Bot configuration. */
getByClientId(clientId) {
const found = this.#value.bots.find((bot) => bot.clientId === clientId);
return found ? structuredClone(found) : null;
}
/** @param {object} value Bot configuration without a client secret. @returns {Promise<object>} Saved config. */
async save(value) {
const normalized = normalizeBot(value);
if (!normalized) throw new Error('Refusing to persist invalid dsh-dingtalk bot data');
return this.#mutate((bots) => {
const collision = bots.find(
(bot) => (bot.clientId === normalized.clientId || bot.secretRef === normalized.secretRef)
&& bot.botId !== normalized.botId,
);
if (collision) throw new Error('Duplicate DingTalk bot identity');
const index = bots.findIndex((bot) => bot.botId === normalized.botId);
if (index === -1) bots.push(normalized);
else bots[index] = normalized;
return structuredClone(normalized);
});
}
/** @param {string} botId Derived bot ID. @returns {Promise<object|null>} Removed config. */
async remove(botId) {
if (!safeBotId(botId)) throw new TypeError('Invalid DingTalk 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);
});
}
/** Removes the configuration file and resets the in-memory store. */
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}.${process.pid}.${randomUUID()}.tmp`;
try {
await writeFile(temporary, `${JSON.stringify(storedDocument(document), null, 2)}\n`, {
encoding: 'utf8',
flag: 'wx',
mode: 0o600,
});
await rename(temporary, this.#path);
} catch (error) {
try {
await unlink(temporary);
} catch (cleanupError) {
if (cleanupError?.code !== 'ENOENT') throw new AggregateError([error, cleanupError]);
}
throw error;
}
}
}
export { deriveDingtalkBotIdentity as deriveDingTalkBotIdentity };
export { deriveDingtalkSenderKey as deriveDingTalkSenderKey };
export { maskDingtalkClientId as maskDingTalkClientId };
export { maskDingtalkSenderId as maskDingTalkSenderId };
export { DingtalkConfigStore as DingTalkConfigStore };

View file

@ -0,0 +1,237 @@
const DEFAULT_REGISTRATION_BASE_URL = 'https://oapi.dingtalk.com';
const REGISTRATION_SOURCE = 'DING_DWS_CLAW';
function cleanString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function positiveNumber(value, fallback) {
const number = Number(value);
return Number.isFinite(number) && number > 0 ? number : fallback;
}
function normalizeBaseUrl(value) {
let url;
try {
url = new URL(cleanString(value) ?? DEFAULT_REGISTRATION_BASE_URL);
} catch {
throw new TypeError('DingTalk registration base URL must be a valid HTTPS URL');
}
const isDingtalkHost = url.hostname === 'dingtalk.com' || url.hostname.endsWith('.dingtalk.com');
if (url.protocol !== 'https:'
|| url.port
|| !isDingtalkHost
|| url.username
|| url.password
|| url.search
|| url.hash) {
throw new TypeError('DingTalk registration base URL must be a valid HTTPS URL');
}
url.pathname = url.pathname.replace(/\/+$/, '');
return url.href.replace(/\/$/, '');
}
function readNow(clock) {
const value = typeof clock?.now === 'function' ? clock.now() : clock();
if (!Number.isFinite(value)) throw new TypeError('clock must return a finite timestamp');
return value;
}
function assertRecord(value, action) {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new DingtalkDeviceAuthError(
'invalid-response',
`DingTalk ${action} returned an invalid response`,
action,
);
}
if (Number(value.errcode) !== 0) {
throw new DingtalkDeviceAuthError(
'api-error',
`DingTalk ${action} request was rejected`,
action,
);
}
return value;
}
/** A sanitized DingTalk device-registration failure. */
export class DingtalkDeviceAuthError extends Error {
/**
* @param {string} code Stable failure code.
* @param {string} message Safe diagnostic that does not include response credentials.
* @param {string} action Registration stage that failed.
* @param {{cause?: unknown}} [options] Optional underlying error.
*/
constructor(code, message, action, options = {}) {
super(message, options);
this.name = 'DingtalkDeviceAuthError';
this.code = code;
this.action = action;
}
}
/** Host-only client for DingTalk's QR device-registration flow. */
export class DingtalkDeviceAuth {
#fetch;
#clock;
#baseUrl;
#timeoutMs;
/**
* @param {{fetch?: typeof globalThis.fetch, clock?: {now(): number}|(()=>number), baseUrl?: string, timeoutMs?: number}} [options]
* Device-registration dependencies.
*/
constructor({
fetch = globalThis.fetch,
clock = Date,
baseUrl = DEFAULT_REGISTRATION_BASE_URL,
timeoutMs = 15_000,
} = {}) {
if (typeof fetch !== 'function') throw new TypeError('fetch is required');
if (typeof clock !== 'function' && typeof clock?.now !== 'function') {
throw new TypeError('clock must be a function or expose now()');
}
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
throw new TypeError('timeoutMs must be a positive number');
}
this.#fetch = fetch;
this.#clock = clock;
this.#baseUrl = normalizeBaseUrl(baseUrl);
this.#timeoutMs = timeoutMs;
}
/**
* Starts a QR registration and returns the host-only device code with QR metadata.
* @param {{signal?: AbortSignal}} [options] Optional cancellation signal.
* @returns {Promise<object>} Device registration details.
*/
async start({ signal } = {}) {
const initialized = await this.#post(
'/app/registration/init',
{ source: REGISTRATION_SOURCE },
'initialization',
signal,
);
const nonce = cleanString(initialized.nonce);
if (!nonce) {
throw new DingtalkDeviceAuthError(
'missing-nonce',
'DingTalk registration initialization did not return a nonce',
'initialization',
);
}
const begun = await this.#post(
'/app/registration/begin',
{ nonce },
'begin',
signal,
);
const deviceCode = cleanString(begun.device_code);
const verificationUrl = cleanString(begun.verification_uri_complete);
if (!deviceCode || !verificationUrl) {
throw new DingtalkDeviceAuthError(
'incomplete-registration',
'DingTalk registration did not return complete QR metadata',
'begin',
);
}
const expiresInSeconds = positiveNumber(begun.expires_in, 7_200);
const pollIntervalMs = positiveNumber(begun.interval, 5) * 1_000;
return Object.freeze({
deviceCode,
verificationUrl,
verificationUri: cleanString(begun.verification_uri),
userCode: cleanString(begun.user_code),
expiresAt: readNow(this.#clock) + expiresInSeconds * 1_000,
pollIntervalMs,
});
}
/**
* Polls one registration attempt.
* @param {{deviceCode: string, signal?: AbortSignal}|string} request Host-only device code.
* @returns {Promise<object>} Normalized registration state and credentials on success.
*/
async poll(request) {
const deviceCode = cleanString(typeof request === 'string' ? request : request?.deviceCode);
const signal = typeof request === 'object' ? request?.signal : undefined;
if (!deviceCode) throw new TypeError('deviceCode is required');
const response = await this.#post(
'/app/registration/poll',
{ device_code: deviceCode },
'poll',
signal,
);
const rawStatus = cleanString(response.status)?.toUpperCase();
const status = ['WAITING', 'SUCCESS', 'FAIL', 'EXPIRED'].includes(rawStatus)
? rawStatus
: 'UNKNOWN';
return Object.freeze({
status,
clientId: cleanString(response.client_id),
clientSecret: cleanString(response.client_secret),
failReason: cleanString(response.fail_reason),
});
}
async #post(path, body, action, signal) {
let response;
const timeoutSignal = AbortSignal.timeout(this.#timeoutMs);
const requestSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
try {
response = await this.#fetch(`${this.#baseUrl}${path}`, {
method: 'POST',
headers: {
accept: 'application/json',
'content-type': 'application/json',
},
body: JSON.stringify(body),
redirect: 'error',
signal: requestSignal,
});
} catch (error) {
if (signal?.aborted) throw signal.reason ?? error;
if (timeoutSignal.aborted) {
throw new DingtalkDeviceAuthError(
'timeout',
`DingTalk ${action} request timed out`,
action,
{ cause: error },
);
}
if (error?.name === 'AbortError') throw error;
throw new DingtalkDeviceAuthError(
'network-error',
`DingTalk ${action} request could not be completed`,
action,
{ cause: error },
);
}
if (!response || response.ok === false || typeof response.json !== 'function') {
throw new DingtalkDeviceAuthError(
'http-error',
`DingTalk ${action} request failed`,
action,
);
}
let value;
try {
value = await response.json();
} catch (error) {
throw new DingtalkDeviceAuthError(
'invalid-json',
`DingTalk ${action} returned invalid JSON`,
action,
{ cause: error },
);
}
return assertRecord(value, action);
}
}
export { DEFAULT_REGISTRATION_BASE_URL, REGISTRATION_SOURCE };
export { DingtalkDeviceAuth as DingTalkDeviceAuth };
export { DingtalkDeviceAuthError as DingTalkDeviceAuthError };

View file

@ -0,0 +1,579 @@
import { randomUUID } from 'node:crypto';
export const DINGTALK_REGISTRATION_BASE_URL = 'https://oapi.dingtalk.com/';
export const DINGTALK_API_BASE_URL = 'https://api.dingtalk.com/';
export const DINGTALK_REGISTRATION_SOURCE = 'DING_DWS_CLAW';
export const DINGTALK_AI_CARD_TEMPLATE_ID = '02fcf2f4-5e02-4a85-b672-46d1f715543e.schema';
const DEFAULT_TIMEOUT_MS = 15_000;
const REGISTRATION_STATUSES = new Set(['WAITING', 'SUCCESS', 'FAIL', 'EXPIRED']);
export class DingtalkApiError extends Error {
constructor(code, message, options = {}) {
super(message, options);
this.name = 'DingtalkApiError';
this.code = code;
this.status = options.status;
}
}
function nonEmptyString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function isDingtalkHost(hostname) {
const normalized = hostname.toLowerCase().replace(/\.$/, '');
return normalized === 'dingtalk.com' || normalized.endsWith('.dingtalk.com');
}
function normalizeTrustedUrl(value, { label, requireSubdomain = true } = {}) {
let url;
try {
url = new URL(value);
} catch {
throw new DingtalkApiError('invalid-url', `${label ?? '钉钉服务'}返回了无效地址。`);
}
const normalizedHost = url.hostname.toLowerCase().replace(/\.$/, '');
const trustedHost = requireSubdomain
? normalizedHost !== 'dingtalk.com' && isDingtalkHost(normalizedHost)
: isDingtalkHost(normalizedHost);
if (url.protocol !== 'https:' || !trustedHost || (url.port && url.port !== '443')) {
throw new DingtalkApiError('untrusted-url', `${label ?? '钉钉服务'}地址不受信任。`);
}
if (url.username || url.password) {
throw new DingtalkApiError('untrusted-url', `${label ?? '钉钉服务'}地址不受信任。`);
}
return url;
}
export function normalizeDingtalkSessionWebhook(value) {
const text = nonEmptyString(value);
if (!text) throw new DingtalkApiError('invalid-session-webhook', '钉钉消息没有可用的回复地址。');
const url = normalizeTrustedUrl(text, { label: '钉钉回复', requireSubdomain: false });
url.hash = '';
return url.toString();
}
export function splitDingtalkText(value, maxChars = 4_000) {
const text = typeof value === 'string' ? value.trim() : '';
if (!text) return [];
if (!Number.isInteger(maxChars) || maxChars < 1) throw new TypeError('maxChars must be a positive integer');
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;
}
function abortError(signal) {
if (signal?.reason instanceof Error) return signal.reason;
return new DOMException('The operation was aborted', 'AbortError');
}
function abortableDelay(ms, signal) {
if (ms <= 0) return Promise.resolve();
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(abortError(signal));
return;
}
const timer = setTimeout(() => {
signal?.removeEventListener('abort', onAbort);
resolve();
}, ms);
const onAbort = () => {
clearTimeout(timer);
reject(abortError(signal));
};
signal?.addEventListener('abort', onAbort, { once: true });
});
}
async function requestJson(fetchImpl, url, {
body,
signal,
timeoutMs = DEFAULT_TIMEOUT_MS,
headers = {},
method = 'POST',
action = 'request',
} = {}) {
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,
redirect: 'error',
headers: { 'content-type': 'application/json', ...headers },
body: JSON.stringify(body ?? {}),
signal: controller.signal,
});
if (!response.ok) {
throw new DingtalkApiError(
'http-error',
`钉钉服务请求失败(HTTP ${response.status})。`,
{ status: response.status },
);
}
try {
return await response.json();
} catch (error) {
throw new DingtalkApiError('invalid-response', '钉钉服务返回了无法解析的响应。', { cause: error });
}
} catch (error) {
if (signal?.aborted) throw abortError(signal);
if (timedOut) throw new DingtalkApiError('timeout', '钉钉服务请求超时。', { cause: error });
if (error instanceof DingtalkApiError) throw error;
throw new DingtalkApiError('network-error', `暂时无法完成钉钉${action}请求。`, { cause: error });
} finally {
if (timer) clearTimeout(timer);
signal?.removeEventListener('abort', onAbort);
}
}
function normalizeCardTarget(target) {
if (target?.type === 'user') {
const userId = nonEmptyString(target.userId);
if (userId) return { type: 'user', userId };
}
if (target?.type === 'group') {
const openConversationId = nonEmptyString(target.openConversationId);
if (openConversationId) return { type: 'group', openConversationId };
}
throw new TypeError('DingTalk AI Card target is invalid');
}
function cardData(text, flowStatus) {
return {
cardParamMap: {
flowStatus,
msgContent: normalizeDingtalkCardMarkdown(text),
staticMsgContent: '',
sys_full_json_obj: JSON.stringify({ order: ['msgContent'] }),
config: JSON.stringify({ autoLayout: true }),
},
};
}
function cardDeliverBody(cardInstanceId, target, robotCode) {
const base = { outTrackId: cardInstanceId, userIdType: 1 };
if (target.type === 'group') {
return {
...base,
openSpaceId: `dtv1.card//IM_GROUP.${target.openConversationId}`,
imGroupOpenDeliverModel: { robotCode },
};
}
return {
...base,
openSpaceId: `dtv1.card//IM_ROBOT.${target.userId}`,
imRobotOpenDeliverModel: {
spaceType: 'IM_ROBOT',
robotCode,
extension: { dynamicSummary: 'true' },
},
};
}
export function normalizeDingtalkCardMarkdown(value) {
const text = typeof value === 'string' ? value.replace(/\r\n?/g, '\n') : '';
const lines = text.split('\n');
let inCodeBlock = false;
return lines.map((line, index) => {
const fenced = /^\s{0,3}```/.test(line);
const currentInCodeBlock = inCodeBlock;
if (fenced) inCodeBlock = !inCodeBlock;
if (index === lines.length - 1) return line;
if (currentInCodeBlock || fenced || inCodeBlock || !line || !lines[index + 1]) return `${line}\n`;
if (/^\s{0,3}(?:[-*+] |\d+[.)] |#{1,6} |\||> )/.test(lines[index + 1])) return `${line}\n`;
return `${line}<br>`;
}).join('');
}
function assertRegistrationOk(value, action) {
if (!value || typeof value !== 'object' || value.errcode !== 0) {
throw new DingtalkApiError(
'registration-rejected',
`钉钉扫码${action}失败。`,
);
}
return value;
}
function positiveNumber(value, fallback) {
const number = Number(value);
return Number.isFinite(number) && number > 0 ? number : fallback;
}
export function createDingtalkApi({
fetchImpl = fetch,
registrationBaseUrl = process.env.DINGTALK_REGISTRATION_BASE_URL
|| DINGTALK_REGISTRATION_BASE_URL,
registrationSource = process.env.DINGTALK_REGISTRATION_SOURCE
|| DINGTALK_REGISTRATION_SOURCE,
now = () => Date.now(),
cardMinIntervalMs = 50,
cardBackoffMs = 1_000,
delay = abortableDelay,
} = {}) {
if (typeof fetchImpl !== 'function') throw new TypeError('fetchImpl must be a function');
if (typeof now !== 'function') throw new TypeError('now must be a function');
if (!Number.isFinite(cardMinIntervalMs) || cardMinIntervalMs < 0) {
throw new TypeError('cardMinIntervalMs must be a non-negative number');
}
if (!Number.isFinite(cardBackoffMs) || cardBackoffMs < 0) {
throw new TypeError('cardBackoffMs must be a non-negative number');
}
if (typeof delay !== 'function') throw new TypeError('delay must be a function');
const registrationBase = normalizeTrustedUrl(registrationBaseUrl, {
label: '钉钉注册服务',
requireSubdomain: false,
});
const apiBase = new URL(DINGTALK_API_BASE_URL);
const source = nonEmptyString(registrationSource);
if (!source) throw new TypeError('registrationSource is required');
const tokenCache = new Map();
const tokenRequests = new Map();
let cardSlotTail = Promise.resolve();
let nextCardRequestAt = 0;
const endpoint = (base, pathname) => new URL(pathname.replace(/^\//, ''), base);
async function accessToken({ clientId, clientSecret, signal }) {
const appKey = nonEmptyString(clientId);
const appSecret = nonEmptyString(clientSecret);
if (!appKey || !appSecret) throw new TypeError('clientId and clientSecret are required');
const cached = tokenCache.get(appKey);
if (cached && cached.expiresAt > now()) return cached.token;
if (tokenRequests.has(appKey)) return tokenRequests.get(appKey);
const request = (async () => {
const value = await requestJson(fetchImpl, endpoint(apiBase, 'v1.0/oauth2/accessToken'), {
body: { appKey, appSecret },
signal,
action: '鉴权',
});
const token = nonEmptyString(value?.accessToken);
if (!token) throw new DingtalkApiError('invalid-access-token', '钉钉服务没有返回访问令牌。');
const expiresInSeconds = positiveNumber(value?.expireIn ?? value?.expiresIn, 7_200);
const refreshAfterMs = Math.max(1_000, (expiresInSeconds - 60) * 1_000);
tokenCache.set(appKey, { token, expiresAt: now() + refreshAfterMs });
return token;
})().finally(() => tokenRequests.delete(appKey));
tokenRequests.set(appKey, request);
return request;
}
function acquireCardRequestSlot(signal) {
const acquire = async () => {
const waitMs = Math.max(0, nextCardRequestAt - now());
if (waitMs > 0) await delay(waitMs, signal);
nextCardRequestAt = Math.max(nextCardRequestAt, now()) + cardMinIntervalMs;
};
const slot = cardSlotTail.then(acquire, acquire);
cardSlotTail = slot.catch(() => undefined);
return slot;
}
async function cardRequest(pathname, options) {
await acquireCardRequestSlot(options.signal);
try {
return await requestJson(fetchImpl, endpoint(apiBase, pathname), options);
} catch (error) {
if (!(error instanceof DingtalkApiError) || error.status !== 403) throw error;
await delay(cardBackoffMs, options.signal);
await acquireCardRequestSlot(options.signal);
return requestJson(fetchImpl, endpoint(apiBase, pathname), options);
}
}
async function failCard({ clientId, clientSecret, cardInstanceId, text, signal }) {
const instanceId = nonEmptyString(cardInstanceId);
const content = nonEmptyString(text);
if (!instanceId) throw new TypeError('cardInstanceId is required');
if (!content) throw new TypeError('text is required');
const token = await accessToken({ clientId, clientSecret, signal });
const headers = { 'x-acs-dingtalk-access-token': token };
const requests = [
cardRequest('v1.0/card/streaming', {
method: 'PUT',
body: {
outTrackId: instanceId,
guid: randomUUID(),
key: 'msgContent',
content: normalizeDingtalkCardMarkdown(content),
isFull: true,
isFinalize: false,
isError: true,
},
headers,
signal,
action: 'AI Card 失败收口',
}),
cardRequest('v1.0/card/instances', {
method: 'PUT',
body: {
outTrackId: instanceId,
cardData: cardData(content, '5'),
cardUpdateOptions: { updateCardDataByKey: true },
},
headers,
signal,
action: 'AI Card 失败状态',
}),
];
const results = await Promise.allSettled(requests);
if (results.every(({ status }) => status === 'rejected')) throw results[0].reason;
return true;
}
return Object.freeze({
async beginRegistration({ signal } = {}) {
const initialized = assertRegistrationOk(await requestJson(
fetchImpl,
endpoint(registrationBase, 'app/registration/init'),
{ body: { source }, signal, action: '初始化' },
), '初始化');
const nonce = nonEmptyString(initialized.nonce);
if (!nonce) throw new DingtalkApiError('invalid-registration', '钉钉扫码初始化缺少 nonce。');
const begun = assertRegistrationOk(await requestJson(
fetchImpl,
endpoint(registrationBase, 'app/registration/begin'),
{ body: { nonce }, signal, action: '创建' },
), '创建');
const deviceCode = nonEmptyString(begun.device_code);
const verificationUriComplete = nonEmptyString(begun.verification_uri_complete);
if (!deviceCode || !verificationUriComplete) {
throw new DingtalkApiError('invalid-registration', '钉钉扫码服务返回的信息不完整。');
}
const verificationUrl = normalizeTrustedUrl(verificationUriComplete, {
label: '钉钉扫码',
requireSubdomain: false,
}).toString();
return {
deviceCode,
userCode: nonEmptyString(begun.user_code) ?? undefined,
verificationUri: nonEmptyString(begun.verification_uri) ?? undefined,
verificationUriComplete: verificationUrl,
expiresInSeconds: positiveNumber(begun.expires_in, 7_200),
intervalSeconds: positiveNumber(begun.interval, 5),
};
},
async pollRegistration({ deviceCode, signal } = {}) {
const code = nonEmptyString(deviceCode);
if (!code) throw new TypeError('deviceCode is required');
const polled = assertRegistrationOk(await requestJson(
fetchImpl,
endpoint(registrationBase, 'app/registration/poll'),
{ body: { device_code: code }, signal, action: '状态查询' },
), '状态查询');
const status = nonEmptyString(polled.status)?.toUpperCase();
if (!status || !REGISTRATION_STATUSES.has(status)) {
throw new DingtalkApiError('invalid-registration-status', '钉钉扫码服务返回了无法识别的状态。');
}
const result = {
status,
failReason: nonEmptyString(polled.fail_reason) ?? undefined,
};
if (status === 'SUCCESS') {
result.clientId = nonEmptyString(polled.client_id) ?? undefined;
result.clientSecret = nonEmptyString(polled.client_secret) ?? undefined;
if (!result.clientId || !result.clientSecret) {
throw new DingtalkApiError('missing-credentials', '钉钉扫码已确认,但没有返回机器人凭据。');
}
}
return result;
},
accessToken,
async createAiCard({ clientId, clientSecret, target, initialText, signal }) {
const appKey = nonEmptyString(clientId);
const appSecret = nonEmptyString(clientSecret);
const content = nonEmptyString(initialText);
if (!appKey || !appSecret) throw new TypeError('clientId and clientSecret are required');
if (!content) throw new TypeError('initialText is required');
const normalizedTarget = normalizeCardTarget(target);
const token = await accessToken({ clientId: appKey, clientSecret: appSecret, signal });
const cardInstanceId = `dsh_${randomUUID()}`;
const headers = { 'x-acs-dingtalk-access-token': token };
let delivered = false;
try {
await cardRequest('v1.0/card/instances', {
body: {
cardTemplateId: DINGTALK_AI_CARD_TEMPLATE_ID,
outTrackId: cardInstanceId,
cardData: {
cardParamMap: { config: JSON.stringify({ autoLayout: true }) },
},
callbackType: 'STREAM',
imGroupOpenSpaceModel: { supportForward: true },
imRobotOpenSpaceModel: { supportForward: true },
},
headers,
signal,
action: 'AI Card 创建',
});
await cardRequest('v1.0/card/instances/deliver', {
body: cardDeliverBody(cardInstanceId, normalizedTarget, appKey),
headers,
signal,
action: 'AI Card 投放',
});
delivered = true;
await cardRequest('v1.0/card/instances', {
method: 'PUT',
body: { outTrackId: cardInstanceId, cardData: cardData(content, '2') },
headers,
signal,
action: 'AI Card 启动',
});
await cardRequest('v1.0/card/streaming', {
method: 'PUT',
body: {
outTrackId: cardInstanceId,
guid: randomUUID(),
key: 'msgContent',
content: normalizeDingtalkCardMarkdown(content).replace(/\n+$/, ''),
isFull: true,
isFinalize: false,
isError: false,
},
headers,
signal,
action: 'AI Card 启动',
});
} catch (error) {
if (delivered) {
const cleanupSignal = AbortSignal.timeout(5_000);
await failCard({
clientId: appKey,
clientSecret: appSecret,
cardInstanceId,
text: '消息处理失败,请稍后重试。',
signal: cleanupSignal,
}).catch(() => undefined);
}
throw error;
}
return { cardInstanceId };
},
async updateAiCard({ clientId, clientSecret, cardInstanceId, text, signal }) {
const instanceId = nonEmptyString(cardInstanceId);
const content = nonEmptyString(text);
if (!instanceId) throw new TypeError('cardInstanceId is required');
if (!content) throw new TypeError('text is required');
const token = await accessToken({ clientId, clientSecret, signal });
await cardRequest('v1.0/card/streaming', {
method: 'PUT',
body: {
outTrackId: instanceId,
guid: randomUUID(),
key: 'msgContent',
content: normalizeDingtalkCardMarkdown(content).replace(/\n+$/, ''),
isFull: true,
isFinalize: false,
isError: false,
},
headers: { 'x-acs-dingtalk-access-token': token },
signal,
action: 'AI Card 更新',
});
return true;
},
async finishAiCard({ clientId, clientSecret, cardInstanceId, text, signal }) {
const instanceId = nonEmptyString(cardInstanceId);
const content = nonEmptyString(text);
if (!instanceId) throw new TypeError('cardInstanceId is required');
if (!content) throw new TypeError('text is required');
const token = await accessToken({ clientId, clientSecret, signal });
const headers = { 'x-acs-dingtalk-access-token': token };
const normalizedContent = normalizeDingtalkCardMarkdown(content);
await cardRequest('v1.0/card/streaming', {
method: 'PUT',
body: {
outTrackId: instanceId,
guid: randomUUID(),
key: 'msgContent',
content: normalizedContent,
isFull: true,
isFinalize: true,
isError: false,
},
headers,
signal,
action: 'AI Card 完成',
});
let completed = true;
const completionRequest = {
method: 'PUT',
body: {
outTrackId: instanceId,
cardData: cardData(content, '3'),
cardUpdateOptions: { updateCardDataByKey: true },
},
headers,
signal,
action: 'AI Card 收口',
};
try {
await cardRequest('v1.0/card/instances', completionRequest);
} catch {
try {
await cardRequest('v1.0/card/instances', completionRequest);
} catch {
completed = false;
}
}
return { delivered: true, completed };
},
failAiCard: failCard,
async sendText({ clientId, clientSecret, sessionWebhook, text, signal }) {
const content = nonEmptyString(text);
if (!content) throw new TypeError('text is required');
const webhook = normalizeDingtalkSessionWebhook(sessionWebhook);
const token = await accessToken({ clientId, clientSecret, signal });
const response = await requestJson(fetchImpl, webhook, {
body: { msgtype: 'text', text: { content } },
headers: { 'x-acs-dingtalk-access-token': token },
signal,
action: '消息回复',
});
if ((response?.errcode !== undefined && response.errcode !== 0)
|| (response?.code !== undefined && response.code !== 0)) {
throw new DingtalkApiError('send-rejected', '钉钉服务拒绝了回复消息。');
}
return true;
},
clearAccessToken(clientId) {
const appKey = nonEmptyString(clientId);
if (appKey) tokenCache.delete(appKey);
},
});
}
export const createDingTalkApi = createDingtalkApi;
export const normalizeDingTalkSessionWebhook = normalizeDingtalkSessionWebhook;
export const splitDingTalkText = splitDingtalkText;

View file

@ -0,0 +1,281 @@
import {
normalizeDingtalkSessionWebhook,
splitDingtalkText,
} from './dingtalk-api.mjs';
import { createDingTalkCardStream } from './dingtalk-card-stream.mjs';
const CARD_INITIAL_TEXT = '已连接 DeepSeek Harness,正在思考…';
const CARD_ERROR_TEXT = '消息处理失败,请稍后重试。';
const HELP_TEXT = [
'钉钉机器人已连接 DeepSeek Harness。',
'',
'直接发送文字即可继续当前会话。',
'/new 开启一个全新会话',
'/status 检查连接状态',
'/help 显示本帮助',
].join('\n');
function nonEmptyString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function senderStaffId(message) {
return nonEmptyString(message?.senderStaffId) ?? nonEmptyString(message?.senderId);
}
function conversationKey(message, sender) {
if (String(message?.conversationType) === '2') {
const conversationId = nonEmptyString(message?.conversationId);
if (!conversationId) throw new Error('DingTalk group message has no conversation id');
return `group:${conversationId}`;
}
return `p2p:${sender}`;
}
function cardTarget(message, sender) {
if (String(message?.conversationType) === '2') {
return { type: 'group', openConversationId: nonEmptyString(message?.conversationId) };
}
return { type: 'user', userId: sender };
}
function progressText(update) {
if (update?.type === 'text' && nonEmptyString(update.text)) return update.text;
if (update?.type === 'tool') {
if (update.name === 'web_search') return '_正在搜索网络并整理信息…_';
return `_正在使用 ${nonEmptyString(update.name) ?? '工具'}…_`;
}
return `_${nonEmptyString(update?.text) ?? '正在处理…'}_`;
}
function ensureStats(status) {
status.stats ??= {};
for (const key of ['messagesReceived', 'messagesReplied', 'messagesRejected', 'messagesIgnored']) {
status[key] ??= 0;
status.stats[key] = status[key];
}
status.pendingSenders ??= [];
}
function increment(status, key) {
status[key] = (status[key] ?? 0) + 1;
status.stats ??= {};
status.stats[key] = status[key];
}
export function createDingtalkBridgeStatus({ pendingSenders = [] } = {}) {
return {
messagesReceived: 0,
messagesReplied: 0,
messagesRejected: 0,
messagesIgnored: 0,
lastMessageAt: null,
lastReplyAt: null,
lastRejectedAt: null,
lastError: null,
pendingSenders: structuredClone(pendingSenders),
stats: {
messagesReceived: 0,
messagesReplied: 0,
messagesRejected: 0,
messagesIgnored: 0,
},
};
}
export class DingtalkHarnessBridge {
#api;
#clientId;
#clientSecret;
#harness;
#state;
#status;
#logger;
#replyTimeoutMs;
#maxMessageChars;
#signal;
#queues = new Map();
#acceptedMessageIds = new Set();
constructor({
api,
clientId,
clientSecret,
harness,
state,
status = createDingtalkBridgeStatus(),
logger = console,
replyTimeoutMs = 600_000,
maxMessageChars = 4_000,
signal,
}) {
if (!api || typeof api.sendText !== 'function') throw new TypeError('DingTalk API is required');
if (!nonEmptyString(clientId) || !nonEmptyString(clientSecret)) {
throw new TypeError('DingTalk app credentials are required');
}
if (!harness || !state) throw new TypeError('Harness client and state store are required');
this.#api = api;
this.#clientId = clientId.trim();
this.#clientSecret = clientSecret.trim();
this.#harness = harness;
this.#state = state;
this.#status = status;
this.#logger = logger;
this.#replyTimeoutMs = replyTimeoutMs;
this.#maxMessageChars = maxMessageChars;
this.#signal = signal;
ensureStats(this.#status);
this.#refreshPendingSenders();
}
get status() {
this.#refreshPendingSenders();
return structuredClone(this.#status);
}
accept(message) {
if (this.#signal?.aborted) return Promise.resolve();
const messageId = nonEmptyString(message?.msgId);
const sender = senderStaffId(message);
if (!messageId || !sender || this.#state.hasSeen(messageId)
|| this.#acceptedMessageIds.has(messageId)) return Promise.resolve();
this.#acceptedMessageIds.add(messageId);
let key;
try {
key = conversationKey(message, sender);
} catch {
this.#acceptedMessageIds.delete(messageId);
increment(this.#status, 'messagesRejected');
this.#status.lastRejectedAt = new Date().toISOString();
return Promise.resolve();
}
const previous = this.#queues.get(key) ?? Promise.resolve();
const current = previous
.catch(() => undefined)
.then(() => this.#process(message, messageId, sender, key))
.finally(() => {
this.#acceptedMessageIds.delete(messageId);
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, messageId, sender, key) {
this.#signal?.throwIfAborted();
if (this.#state.hasSeen(messageId)) return;
await this.#state.markSeen(messageId);
increment(this.#status, 'messagesReceived');
this.#status.lastMessageAt = new Date().toISOString();
if (String(message.conversationType) === '2' && message.isInAtList !== true) {
increment(this.#status, 'messagesIgnored');
return;
}
let sessionWebhook;
try {
sessionWebhook = normalizeDingtalkSessionWebhook(message.sessionWebhook);
} catch {
increment(this.#status, 'messagesRejected');
this.#status.lastRejectedAt = new Date().toISOString();
this.#status.lastError = '钉钉消息没有安全的回复地址。';
return;
}
const text = message?.msgtype === 'text' ? nonEmptyString(message?.text?.content) : null;
let cardStream = null;
let cardStarted = false;
try {
if (!text) {
await this.#send(sessionWebhook, '目前仅支持文字消息。');
return;
}
const command = text.toLowerCase();
if (command === '/help') {
await this.#send(sessionWebhook, HELP_TEXT);
return;
}
if (command === '/status') {
await this.#harness.ensureRunning({ signal: this.#signal });
await this.#send(sessionWebhook, '钉钉机器人与 DeepSeek Harness 连接正常。');
return;
}
if (command === '/new') {
await this.#state.clearSession(key);
await this.#send(sessionWebhook, '已开启新会话。请发送你的问题。');
return;
}
let sessionId = this.#state.sessionFor(key);
if (!sessionId || !(await this.#harness.sessionExists(sessionId, { signal: this.#signal }))) {
sessionId = await this.#harness.createSession({ signal: this.#signal });
await this.#state.setSession(key, sessionId);
}
if (typeof this.#api.createAiCard === 'function'
&& typeof this.#api.updateAiCard === 'function'
&& typeof this.#api.finishAiCard === 'function') {
cardStream = createDingTalkCardStream({
api: this.#api,
clientId: this.#clientId,
clientSecret: this.#clientSecret,
target: cardTarget(message, sender),
signal: this.#signal,
logger: this.#logger,
});
cardStarted = await cardStream.start(CARD_INITIAL_TEXT);
}
const answer = await this.#harness.ask(sessionId, text, {
timeoutMs: this.#replyTimeoutMs,
signal: this.#signal,
onUpdate: cardStarted
? (update) => cardStream.push(progressText(update))
: undefined,
});
const streamed = cardStarted && await cardStream.finish(answer);
if (!streamed) await this.#send(sessionWebhook, answer);
increment(this.#status, 'messagesReplied');
this.#status.lastReplyAt = new Date().toISOString();
this.#status.lastError = null;
} catch {
if (this.#signal?.aborted) return;
this.#status.lastError = '钉钉消息处理失败。';
this.#logger.error?.('[dsh-dingtalk] failed to process an inbound message');
try {
const streamed = cardStarted && await cardStream.finish(CARD_ERROR_TEXT);
if (!streamed) await this.#send(sessionWebhook, CARD_ERROR_TEXT);
} catch {
this.#logger.error?.('[dsh-dingtalk] failed to send the safe error reply');
}
}
}
#refreshPendingSenders() {
if (typeof this.#state.pendingSenders === 'function') {
this.#status.pendingSenders = this.#state.pendingSenders();
}
}
async #send(sessionWebhook, text) {
for (const chunk of splitDingtalkText(text, this.#maxMessageChars)) {
this.#signal?.throwIfAborted();
await this.#api.sendText({
clientId: this.#clientId,
clientSecret: this.#clientSecret,
sessionWebhook,
text: chunk,
signal: this.#signal,
});
}
}
}
export const DingTalkHarnessBridge = DingtalkHarnessBridge;
export const createDingTalkBridgeStatus = createDingtalkBridgeStatus;

View file

@ -0,0 +1,233 @@
const DEFAULT_UPDATE_INTERVAL_MS = 500;
const FAILURE_TEXT = '消息处理失败,请稍后重试。';
function requiredText(value, name) {
if (typeof value !== 'string') throw new TypeError(`${name} must be a string`);
return value;
}
function requiredCredential(value, name) {
if (typeof value !== 'string' || !value.trim()) {
throw new TypeError(`${name} is required`);
}
return value.trim();
}
/**
* Creates one throttled DingTalk AI Card update stream.
*
* The stream owns a single card instance. Progress updates use latest-wins
* buffering, while finish waits for an active update before sending the final
* card content.
*
* @param {object} options Stream dependencies and DingTalk request data.
* @param {object} options.api DingTalk AI Card API implementation.
* @param {string} options.clientId DingTalk application client id.
* @param {string} options.clientSecret DingTalk application client secret.
* @param {unknown} options.target DingTalk card delivery target.
* @param {AbortSignal} [options.signal] Stream cancellation signal.
* @param {object} [options.logger] Safe diagnostic sink.
* @param {number} [options.updateIntervalMs=500] Minimum delay between updates.
* @param {()=>number} [options.clock] Monotonic millisecond clock.
* @param {{setTimeout: Function, clearTimeout: Function}} [options.timer] Timer implementation.
* @returns {{start(initialText: string): Promise<boolean>, push(progressText: string): void, finish(finalText: string): Promise<boolean>}}
* Card stream controller.
*/
export function createDingTalkCardStream({
api,
clientId,
clientSecret,
target,
signal,
logger = console,
updateIntervalMs = DEFAULT_UPDATE_INTERVAL_MS,
clock = () => Date.now(),
timer = {
setTimeout: (callback, delay) => globalThis.setTimeout(callback, delay),
clearTimeout: (handle) => globalThis.clearTimeout(handle),
},
} = {}) {
if (!api
|| typeof api.createAiCard !== 'function'
|| typeof api.updateAiCard !== 'function'
|| typeof api.finishAiCard !== 'function') {
throw new TypeError('DingTalk AI Card API is required');
}
const normalizedClientId = requiredCredential(clientId, 'clientId');
const normalizedClientSecret = requiredCredential(clientSecret, 'clientSecret');
if (target === undefined || target === null) throw new TypeError('target is required');
if (!Number.isFinite(updateIntervalMs) || updateIntervalMs < 0) {
throw new TypeError('updateIntervalMs must be a non-negative number');
}
if (typeof clock !== 'function') throw new TypeError('clock must be a function');
if (typeof timer?.setTimeout !== 'function' || typeof timer?.clearTimeout !== 'function') {
throw new TypeError('timer must provide setTimeout and clearTimeout');
}
const readClock = () => {
const value = clock();
if (!Number.isFinite(value)) throw new TypeError('clock must return a finite timestamp');
return value;
};
readClock();
let phase = signal?.aborted ? 'aborted' : 'idle';
let cardRequest = null;
let pendingText = null;
let scheduledUpdate = null;
let updateWorker = null;
let finishPromise = null;
let cleanupPromise = null;
let lastUpdateAt = 0;
const clearScheduledUpdate = () => {
if (scheduledUpdate === null) return;
timer.clearTimeout(scheduledUpdate);
scheduledUpdate = null;
};
const removeAbortListener = () => signal?.removeEventListener('abort', onAbort);
const close = (nextPhase) => {
phase = nextPhase;
pendingText = null;
clearScheduledUpdate();
removeAbortListener();
};
const cleanupCard = () => {
if (!cardRequest || typeof api.failAiCard !== 'function') return Promise.resolve(false);
if (!cleanupPromise) {
cleanupPromise = api.failAiCard({
...cardRequest,
text: FAILURE_TEXT,
signal: AbortSignal.timeout(5_000),
}).then(
() => true,
() => false,
);
}
return cleanupPromise;
};
const fail = (operation) => {
if (phase === 'failed' || phase === 'finished' || phase === 'aborted') return;
void cleanupCard();
close('failed');
logger?.error?.(`[dsh-dingtalk] AI Card ${operation} failed`);
};
function onAbort() {
if (phase === 'finished' || phase === 'failed' || phase === 'aborted') return;
void cleanupCard();
close('aborted');
}
if (phase !== 'aborted') signal?.addEventListener('abort', onAbort, { once: true });
const launchUpdate = () => {
if (phase !== 'active' || updateWorker || pendingText === null) return;
const delay = Math.max(0, lastUpdateAt + updateIntervalMs - readClock());
if (delay > 0) {
scheduledUpdate = timer.setTimeout(() => {
scheduledUpdate = null;
launchUpdate();
}, delay);
return;
}
const text = pendingText;
pendingText = null;
updateWorker = (async () => {
try {
await api.updateAiCard({ ...cardRequest, text, finished: false });
lastUpdateAt = readClock();
} catch {
if (signal?.aborted || phase === 'aborted') return;
fail('update');
}
})().finally(() => {
updateWorker = null;
if (phase === 'active' && pendingText !== null) launchUpdate();
});
};
const start = async (initialText) => {
requiredText(initialText, 'initialText');
if (phase !== 'idle') return false;
phase = 'starting';
try {
const created = await api.createAiCard({
clientId: normalizedClientId,
clientSecret: normalizedClientSecret,
target,
initialText,
signal,
});
const cardInstanceId = typeof created?.cardInstanceId === 'string'
? created.cardInstanceId.trim()
: '';
if (!cardInstanceId) throw new TypeError('DingTalk did not return a card instance id');
cardRequest = Object.freeze({
clientId: normalizedClientId,
clientSecret: normalizedClientSecret,
target,
cardInstanceId,
signal,
});
if (phase !== 'starting') {
void cleanupCard();
return false;
}
lastUpdateAt = readClock();
phase = 'active';
return true;
} catch {
if (signal?.aborted || phase === 'aborted') {
close('aborted');
return false;
}
fail('creation');
return false;
}
};
const push = (progressText) => {
requiredText(progressText, 'progressText');
if (phase !== 'active') return;
pendingText = progressText;
if (!scheduledUpdate && !updateWorker) launchUpdate();
};
const finish = (finalText) => {
requiredText(finalText, 'finalText');
if (phase === 'finished') return Promise.resolve(true);
if (phase === 'finishing') return finishPromise;
if (phase !== 'active') return Promise.resolve(false);
phase = 'finishing';
pendingText = null;
clearScheduledUpdate();
const activeUpdate = updateWorker;
finishPromise = (async () => {
if (activeUpdate) await activeUpdate;
if (phase !== 'finishing') return false;
try {
await api.finishAiCard({ ...cardRequest, text: finalText });
if (phase !== 'finishing') return false;
close('finished');
return true;
} catch {
if (signal?.aborted || phase === 'aborted') {
close('aborted');
return false;
}
fail('finish');
return false;
}
})();
return finishPromise;
};
return Object.freeze({ start, push, finish });
}

View file

@ -0,0 +1,708 @@
import { randomUUID } from 'node:crypto';
import {
deriveDingtalkBotIdentity,
deriveDingtalkSenderKey,
maskDingtalkClientId,
maskDingtalkSenderId,
} from './config-store.mjs';
const ACTIVE_ATTEMPT_STATES = new Set(['starting', 'pending', 'connecting']);
const TERMINAL_ATTEMPT_STATES = new Set(['connected', 'expired', 'failed', 'cancelled']);
function cleanString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function safeError(code, message) {
return Object.freeze({ code, message });
}
function nowFrom(clock) {
return typeof clock?.now === 'function' ? clock.now() : clock();
}
function isoNow(clock) {
return new Date(nowFrom(clock)).toISOString();
}
function abortError() {
return new DOMException('DingTalk provisioning was cancelled', 'AbortError');
}
function publicAttempt(record) {
if (!record) return null;
return {
attemptId: record.id,
status: record.state,
...(record.verificationUrl ? { verificationUrl: record.verificationUrl } : {}),
...(record.expiresAt ? { expiresAt: record.expiresAt } : {}),
...(record.pollIntervalMs ? { pollIntervalMs: record.pollIntervalMs } : {}),
...(record.botId ? { botId: record.botId } : {}),
...(record.alreadyConnected ? { alreadyConnected: true } : {}),
...(record.error ? { error: structuredClone(record.error) } : {}),
};
}
function runtimeStatus(runtime) {
if (!runtime) return {};
const value = typeof runtime.status === 'function' ? runtime.status() : runtime.status;
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
}
function isRuntimeConnected(runtime, status) {
if (!runtime) return false;
if (status.connected === false || status.ready === false) return false;
const state = cleanString(
status.dingtalkStreamState
?? status.dingtalkConnectionState
?? status.connectionState
?? status.state,
)?.toLowerCase();
if (['failed', 'error', 'offline', 'disconnected', 'stopped'].includes(state)) return false;
return status.connected === true
|| status.ready === true
|| state === 'connected'
|| state === 'ready';
}
function normalizePendingSender(value) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
const staffId = cleanString(value.staffId ?? value.senderStaffId ?? value.senderId);
if (!staffId) return null;
const suppliedRequestId = cleanString(value.requestId);
const opaqueRequestId = suppliedRequestId
&& /^ding_sender_[A-Za-z0-9_-]{1,100}$/.test(suppliedRequestId)
&& !suppliedRequestId.includes(staffId)
? suppliedRequestId
: null;
if (!opaqueRequestId) return null;
return {
requestId: opaqueRequestId,
staffId,
displayName: cleanString(value.displayName ?? value.senderName ?? value.senderNick) ?? '钉钉用户',
requestedAt: cleanString(value.requestedAt),
};
}
function internalPendingSenders(status) {
if (!Array.isArray(status.pendingSenders)) return [];
const seen = new Set();
const senders = [];
for (const value of status.pendingSenders) {
const sender = normalizePendingSender(value);
if (!sender || seen.has(sender.staffId)) continue;
seen.add(sender.staffId);
senders.push(sender);
}
return senders;
}
function publicPendingSender(sender) {
return {
requestId: sender.requestId,
displayName: sender.displayName,
senderIdMasked: maskDingtalkSenderId(sender.staffId),
requestedAt: sender.requestedAt,
};
}
function publicApprovedSender(sender) {
return {
senderKey: sender.senderKey,
displayName: cleanString(sender.displayName) ?? '钉钉用户',
senderIdMasked: maskDingtalkSenderId(sender.staffId),
approvedAt: cleanString(sender.approvedAt),
};
}
/** Coordinates DingTalk QR registration, credentials, runtimes, and sender approvals. */
export class DingtalkController {
#deviceAuth;
#credentials;
#configStore;
#createRuntime;
#deleteState;
#logger;
#clock;
#runtimes = new Map();
#errors = new Map();
#attempts = new Map();
#activeAttemptId = null;
#transitions = new Map();
#revision = 0;
#closed = false;
/**
* @param {object} options Controller dependencies.
* @param {object} options.deviceAuth Host-only DingTalk device auth client.
* @param {object} options.credentials DSH credential provider.
* @param {object} options.configStore Loaded DingTalk config store.
* @param {Function} options.createRuntime Runtime factory.
* @param {Function} [options.deleteState] Per-bot state cleanup callback.
* @param {Console} [options.logger] Host logger.
* @param {{now(): number}|(()=>number)} [options.clock] Injectable clock.
*/
constructor({
deviceAuth,
credentials,
configStore,
createRuntime,
deleteState = async () => {},
logger = console,
clock = Date,
}) {
if (!deviceAuth
|| typeof deviceAuth.start !== 'function'
|| typeof deviceAuth.poll !== 'function') {
throw new TypeError('DingtalkController requires a DingTalk device auth client');
}
if (!credentials
|| typeof credentials.resolve !== 'function'
|| typeof credentials.set !== 'function'
|| typeof credentials.unset !== 'function') {
throw new TypeError('DingtalkController requires the DSH credential provider');
}
if (!configStore
|| typeof configStore.list !== 'function'
|| typeof configStore.get !== 'function'
|| typeof configStore.getByClientId !== 'function'
|| typeof configStore.save !== 'function'
|| typeof configStore.remove !== 'function') {
throw new TypeError('DingtalkController requires a loaded config store');
}
if (typeof createRuntime !== 'function') throw new TypeError('createRuntime is required');
if (typeof deleteState !== 'function') throw new TypeError('deleteState must be a function');
if (typeof clock !== 'function' && typeof clock?.now !== 'function') {
throw new TypeError('clock must be a function or expose now()');
}
this.#deviceAuth = deviceAuth;
this.#credentials = credentials;
this.#configStore = configStore;
this.#createRuntime = createRuntime;
this.#deleteState = deleteState;
this.#logger = logger;
this.#clock = clock;
}
/** Starts all configured DingTalk runtimes whose secrets are available. */
async initialize() {
if (this.#closed) return this.status();
for (const config of this.#configStore.list()) {
const current = this.#runtimes.get(config.botId);
try {
if (isRuntimeConnected(current, runtimeStatus(current))) continue;
} catch {
// A runtime with an unreadable status is replaced below.
}
await this.#withBotTransition(config.botId, async () => {
const latest = this.#configStore.get(config.botId);
if (!latest || this.#closed) return;
const clientSecret = await this.#resolveSecret(latest.secretRef);
if (!clientSecret) {
this.#errors.set(
latest.botId,
safeError('missing-secret', '钉钉机器人凭据缺失,请移除后重新扫码。'),
);
this.#touch();
return;
}
try {
await this.#startRuntime(latest, clientSecret);
this.#errors.delete(latest.botId);
} catch {
this.#errors.set(
latest.botId,
safeError('connection-failed', '钉钉连接未就绪,请稍后重试。'),
);
this.#logger.warn?.(`[dsh-dingtalk] bot ${latest.botId} failed to initialize`);
}
this.#touch();
});
}
return this.status();
}
/** Starts one DingTalk QR registration, cancelling any prior active attempt. */
async startProvisioning({ signal } = {}) {
if (this.#closed) throw new Error('dsh-dingtalk controller is closed');
if (this.#activeAttemptId) await this.cancelProvisioning(this.#activeAttemptId);
const record = {
id: randomUUID(),
state: 'starting',
controller: new AbortController(),
deviceCode: null,
verificationUrl: null,
expiresAt: null,
pollIntervalMs: null,
pollTask: null,
botId: null,
alreadyConnected: false,
error: null,
};
this.#attempts.set(record.id, record);
this.#activeAttemptId = record.id;
this.#touch();
const abortFromRequest = () => record.controller.abort(signal?.reason);
if (signal?.aborted) abortFromRequest();
else signal?.addEventListener('abort', abortFromRequest, { once: true });
try {
const begun = await this.#deviceAuth.start({ signal: record.controller.signal });
this.#assertAttemptActive(record);
record.deviceCode = cleanString(begun.deviceCode);
record.verificationUrl = cleanString(begun.verificationUrl);
record.expiresAt = Number(begun.expiresAt);
record.pollIntervalMs = Number(begun.pollIntervalMs);
if (!record.deviceCode
|| !record.verificationUrl
|| !Number.isFinite(record.expiresAt)
|| !Number.isFinite(record.pollIntervalMs)
|| record.pollIntervalMs <= 0) {
throw new Error('DingTalk device auth returned incomplete registration metadata');
}
record.state = 'pending';
this.#touch();
return publicAttempt(record);
} catch (error) {
if (record.controller.signal.aborted || error?.name === 'AbortError') {
record.state = 'cancelled';
record.error = safeError('cancelled', '扫码接入已取消。');
} else {
record.state = 'failed';
record.error = safeError('qr-start-failed', '无法生成钉钉二维码,请稍后重试。');
}
if (this.#activeAttemptId === record.id) this.#activeAttemptId = null;
this.#touch();
if (record.state === 'failed') throw error;
return publicAttempt(record);
} finally {
signal?.removeEventListener('abort', abortFromRequest);
}
}
/** Polls one QR registration without exposing its device code or returned secret. */
async registrationStatus(attemptId) {
const record = this.#attempts.get(attemptId);
if (!record) return null;
if (TERMINAL_ATTEMPT_STATES.has(record.state) || record.state === 'starting') {
return publicAttempt(record);
}
if (nowFrom(this.#clock) >= record.expiresAt) {
record.state = 'expired';
record.error = safeError('expired', '二维码已过期,请重新生成。');
if (this.#activeAttemptId === record.id) this.#activeAttemptId = null;
this.#touch();
return publicAttempt(record);
}
if (!record.pollTask) {
const task = this.#pollRegistration(record).finally(() => {
if (record.pollTask === task) record.pollTask = null;
});
record.pollTask = task;
}
await record.pollTask;
return publicAttempt(record);
}
/** Cancels an active QR registration. */
async cancelProvisioning(attemptId) {
const record = this.#attempts.get(attemptId);
if (!record) return null;
if (!TERMINAL_ATTEMPT_STATES.has(record.state)) {
record.controller.abort();
await record.pollTask?.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);
}
/** Replaces one bot runtime using its stored credential. */
async reconnectBot(botId) {
const config = this.#configStore.get(botId);
if (!config) throw new Error('Unknown DingTalk bot');
await this.#withBotTransition(botId, async () => {
const clientSecret = await this.#resolveSecret(config.secretRef);
if (!clientSecret) throw new Error('The DingTalk client secret is missing');
try {
await this.#startRuntime(config, clientSecret);
this.#errors.delete(botId);
} catch (error) {
this.#errors.set(
botId,
safeError('connection-failed', '钉钉连接仍未就绪,请稍后重试。'),
);
throw error;
} finally {
this.#touch();
}
});
return this.status();
}
/** Removes one bot, its secret, runtime, and local conversation state. */
async deleteBot(botId) {
const config = this.#configStore.get(botId);
if (!config) throw new Error('Unknown DingTalk bot');
await this.#withBotTransition(botId, async () => {
const previousSecret = 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 (cleanString(previousSecret?.value)) {
await this.#credentials.set(config.secretRef, previousSecret.value).catch(() => undefined);
await this.#startRuntime(config, previousSecret.value).catch(() => undefined);
}
throw new Error('Unable to remove the DingTalk bot safely.', { cause: error });
}
try {
await this.#deleteState({ botId, config });
} catch {
this.#logger.warn?.(`[dsh-dingtalk] bot ${botId} state cleanup failed`);
}
this.#errors.delete(botId);
this.#touch();
});
return this.status();
}
/** Approves one opaque pending-sender request for a bot. */
async approveSender(botId, requestId) {
const config = this.#configStore.get(botId);
if (!config) throw new Error('Unknown DingTalk bot');
const runtime = this.#runtimes.get(botId);
const direct = typeof runtime?.pendingSender === 'function'
? normalizePendingSender(runtime.pendingSender(requestId))
: null;
const pending = internalPendingSenders(runtimeStatus(runtime));
const sender = direct?.requestId === requestId
? direct
: pending.find((candidate) => candidate.requestId === requestId);
if (!sender) throw new Error('Unknown DingTalk sender approval request');
if (config.approvedSenders.some((approved) => approved.staffId === sender.staffId)) {
return this.status();
}
const updated = {
...config,
approvedSenders: [
...config.approvedSenders,
{
senderKey: deriveDingtalkSenderKey(),
staffId: sender.staffId,
displayName: sender.displayName,
approvedAt: isoNow(this.#clock),
},
],
};
await this.#saveAndRestart(config, updated);
return this.status();
}
/** Revokes one approved sender by its browser-safe sender key. */
async revokeSender(botId, senderKey) {
const config = this.#configStore.get(botId);
if (!config) throw new Error('Unknown DingTalk bot');
const index = config.approvedSenders.findIndex(
(sender) => sender.senderKey === senderKey,
);
if (index === -1) throw new Error('Unknown approved DingTalk sender');
const approvedSenders = [...config.approvedSenders];
approvedSenders.splice(index, 1);
await this.#saveAndRestart(config, { ...config, approvedSenders });
return this.status();
}
/** Returns browser-safe bot, health, and sender-approval state. */
status() {
const bots = this.#configStore.list().map((config) => {
const runtime = this.#runtimes.get(config.botId);
let currentStatus = {};
try {
currentStatus = runtimeStatus(runtime);
} catch {
currentStatus = { state: 'error' };
}
const connected = isRuntimeConnected(runtime, currentStatus);
const accountError = this.#errors.get(config.botId);
const state = connected ? 'connected' : accountError ? 'error' : 'offline';
const approvedIds = new Set(config.approvedSenders.map((sender) => sender.staffId));
const pending = internalPendingSenders(currentStatus)
.filter((sender) => !approvedIds.has(sender.staffId))
.map(publicPendingSender);
return {
botId: config.botId,
state,
connected,
configured: true,
bot: {
name: '钉钉机器人',
clientIdMasked: maskDingtalkClientId(config.clientId),
},
health: {
status: connected ? 'healthy' : accountError ? 'error' : 'offline',
summary: connected
? '钉钉 Stream 消息连接运行正常'
: accountError?.message ?? '钉钉消息连接当前离线',
lastCheckedAt: currentStatus.lastCheckedAt ?? null,
},
stats: {
messagesReceived: Number(currentStatus.messagesReceived) || 0,
messagesReplied: Number(currentStatus.messagesReplied) || 0,
},
senders: {
pending,
approved: config.approvedSenders.map(publicApprovedSender),
},
error: accountError ? structuredClone(accountError) : 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) }
: {}),
};
}
/** Cancels provisioning and stops every bot runtime. */
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)));
await Promise.allSettled([...this.#transitions.values()]);
await Promise.allSettled([...this.#runtimes.keys()].map((botId) => this.#stopRuntime(botId)));
}
async #pollRegistration(record) {
try {
this.#assertAttemptActive(record);
const response = await this.#deviceAuth.poll({
deviceCode: record.deviceCode,
signal: record.controller.signal,
});
this.#assertAttemptActive(record);
const state = cleanString(response.status)?.toUpperCase();
if (state === 'WAITING') {
record.state = 'pending';
record.error = null;
} else if (state === 'SUCCESS') {
const clientId = cleanString(response.clientId);
const clientSecret = cleanString(response.clientSecret);
if (!clientId || !clientSecret) throw new Error('DingTalk returned incomplete credentials');
record.state = 'connecting';
record.error = null;
this.#touch();
const activation = await this.#activateBot(record, { clientId, clientSecret });
record.botId = activation.botId;
record.alreadyConnected = activation.alreadyConnected;
record.state = 'connected';
if (this.#activeAttemptId === record.id) this.#activeAttemptId = null;
} else if (state === 'EXPIRED') {
record.state = 'expired';
record.error = safeError('expired', '二维码已过期,请重新生成。');
if (this.#activeAttemptId === record.id) this.#activeAttemptId = null;
} else if (state === 'FAIL') {
record.state = 'failed';
record.error = safeError('authorization-failed', '钉钉未完成机器人授权,请重新扫码。');
if (this.#activeAttemptId === record.id) this.#activeAttemptId = null;
} else {
record.state = 'pending';
record.error = safeError('poll-pending', '钉钉授权状态暂时不可用,正在重试。');
}
} catch (error) {
if (record.controller.signal.aborted || error?.name === 'AbortError') {
record.state = 'cancelled';
record.error = safeError('cancelled', '扫码接入已取消。');
if (this.#activeAttemptId === record.id) this.#activeAttemptId = null;
} else if (record.state === 'connecting') {
record.state = 'failed';
record.error = safeError(
'activation-failed',
'钉钉已授权,但无法安全保存接入配置。',
);
if (this.#activeAttemptId === record.id) this.#activeAttemptId = null;
this.#logger.error?.('[dsh-dingtalk] bot activation failed');
} else {
record.state = 'pending';
record.error = safeError('poll-failed', '钉钉授权查询暂时失败,正在重试。');
}
} finally {
this.#touch();
this.#pruneAttempts();
}
}
async #activateBot(record, { clientId, clientSecret }) {
const identity = deriveDingtalkBotIdentity(clientId);
const previousConfig = this.#configStore.getByClientId(clientId);
const previousSecret = await this.#credentials.resolve(identity.secretRef).catch(() => undefined);
const config = {
botId: identity.botId,
clientId,
secretRef: identity.secretRef,
approvedSenders: previousConfig?.approvedSenders ?? [],
};
return this.#withBotTransition(identity.botId, async () => {
const rollback = async () => {
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.secretRef, previousSecret);
if (previousConfig && cleanString(previousSecret?.value)) {
await this.#startRuntime(previousConfig, previousSecret.value).catch(() => undefined);
}
};
await this.#credentials.set(identity.secretRef, clientSecret);
try {
this.#assertAttemptActive(record);
await this.#configStore.save(config);
this.#assertAttemptActive(record);
} catch (error) {
await rollback();
throw error;
}
try {
await this.#startRuntime(config, clientSecret);
this.#assertAttemptActive(record);
this.#errors.delete(identity.botId);
} catch (error) {
if (record.controller.signal.aborted || this.#activeAttemptId !== record.id) {
await rollback();
throw abortError();
}
this.#errors.set(
identity.botId,
safeError('connection-failed', '钉钉已接入,但消息连接暂未就绪,请稍后重试。'),
);
this.#logger.warn?.('[dsh-dingtalk] authorized bot saved but its connection is not ready');
}
return { botId: identity.botId, alreadyConnected: Boolean(previousConfig) };
});
}
async #saveAndRestart(previousConfig, nextConfig) {
return this.#withBotTransition(previousConfig.botId, async () => {
const clientSecret = await this.#resolveSecret(previousConfig.secretRef);
if (!clientSecret) throw new Error('The DingTalk client secret is missing');
await this.#configStore.save(nextConfig);
try {
await this.#startRuntime(nextConfig, clientSecret);
this.#errors.delete(previousConfig.botId);
} catch (error) {
await this.#configStore.save(previousConfig).catch(() => undefined);
await this.#startRuntime(previousConfig, clientSecret).catch(() => undefined);
this.#errors.set(
previousConfig.botId,
safeError('connection-failed', '钉钉连接未就绪,请稍后重试。'),
);
throw error;
} finally {
this.#touch();
}
});
}
async #startRuntime(config, clientSecret) {
if (this.#closed) throw abortError();
await this.#stopRuntime(config.botId);
if (this.#closed) throw abortError();
const runtime = await this.#createRuntime({
botId: config.botId,
config: structuredClone(config),
clientSecret,
});
if (!runtime || typeof runtime.start !== 'function' || typeof runtime.stop !== 'function') {
throw new TypeError('createRuntime returned an invalid DingTalk runtime');
}
if (this.#closed) {
await runtime.stop().catch(() => undefined);
throw abortError();
}
this.#runtimes.set(config.botId, runtime);
try {
await runtime.start();
if (this.#closed) {
await runtime.stop().catch(() => undefined);
throw abortError();
}
} catch (error) {
if (this.#runtimes.get(config.botId) === runtime) this.#runtimes.delete(config.botId);
await runtime.stop().catch(() => undefined);
throw error;
}
}
async #stopRuntime(botId) {
const runtime = this.#runtimes.get(botId);
this.#runtimes.delete(botId);
await runtime?.stop().catch(() => {
this.#logger.warn?.(`[dsh-dingtalk] bot ${botId} failed to stop cleanly`);
});
}
async #resolveSecret(secretRef) {
const result = await this.#credentials.resolve(secretRef).catch(() => undefined);
return cleanString(result?.value);
}
async #restoreCredential(secretRef, previous) {
try {
if (cleanString(previous?.value)) await this.#credentials.set(secretRef, previous.value);
else await this.#credentials.unset(secretRef);
} catch {
this.#logger.error?.(`[dsh-dingtalk] failed to restore credential ${secretRef}`);
}
}
#assertAttemptActive(record) {
if (record.controller.signal.aborted || this.#activeAttemptId !== record.id) throw abortError();
}
#withBotTransition(botId, operation) {
if (this.#closed) return Promise.reject(new Error('dsh-dingtalk controller is closed'));
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;
}
}
export { DingtalkController as DingTalkController };

View file

@ -0,0 +1,358 @@
import { createDingtalkApi } from './dingtalk-api.mjs';
import {
createDingtalkBridgeStatus,
DingtalkHarnessBridge,
} from './dingtalk-bridge.mjs';
function nonEmptyString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function approvedSenderIds(config) {
const entries = Array.isArray(config?.approvedSenders)
? config.approvedSenders
: config?.approvedSenders instanceof Set
? [...config.approvedSenders]
: [];
return new Set(entries.map((entry) => nonEmptyString(
typeof entry === 'string' ? entry : entry?.staffId,
)).filter(Boolean));
}
function approvedSenderCount(config) {
return approvedSenderIds(config).size;
}
function streamIsOpen(client) {
return client?.connected === true || client?.socket?.readyState === 1;
}
function abortable(promise, signal) {
return new Promise((resolve, reject) => {
if (signal.aborted) {
reject(signal.reason);
return;
}
const onAbort = () => reject(signal.reason);
signal.addEventListener('abort', onAbort, { once: true });
Promise.resolve(promise).then(
(value) => {
signal.removeEventListener('abort', onAbort);
resolve(value);
},
(error) => {
signal.removeEventListener('abort', onAbort);
reject(error);
},
);
});
}
async function waitForStreamOpen(client, pollIntervalMs, signal) {
while (true) {
signal?.throwIfAborted();
if (streamIsOpen(client)) return;
await new Promise((resolve, reject) => {
const timer = setTimeout(() => {
signal?.removeEventListener('abort', onAbort);
resolve();
}, pollIntervalMs);
const onAbort = () => {
clearTimeout(timer);
reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
};
signal?.addEventListener('abort', onAbort, { once: true });
});
}
}
async function connectStream(client, timeoutMs, pollIntervalMs, signal) {
const timeoutSignal = AbortSignal.timeout(timeoutMs);
const connectSignal = AbortSignal.any([signal, timeoutSignal]);
let connectSettled = false;
const connectTask = Promise.resolve()
.then(() => client.connect())
.finally(() => { connectSettled = true; });
try {
await abortable(connectTask, connectSignal);
await waitForStreamOpen(client, pollIntervalMs, connectSignal);
} catch (error) {
if (connectSignal.aborted) {
if (!connectSettled) {
void connectTask.then(() => client.disconnect()).catch(() => undefined);
}
if (signal.aborted) throw signal.reason;
throw new Error(`DingTalk Stream handshake timed out after ${timeoutMs}ms`);
}
throw error;
}
}
async function defaultStreamFactory({ clientId, clientSecret }) {
const { DWClient, TOPIC_ROBOT } = await import('dingtalk-stream');
return {
client: new DWClient({
clientId,
clientSecret,
endpoint: 'https://api.dingtalk.com',
autoReconnect: false,
keepAlive: true,
debug: false,
}),
topic: TOPIC_ROBOT,
};
}
export function createDingtalkRuntimeStatus({
pendingSenders = [],
approvedSenders = 0,
} = {}) {
return {
startedAt: null,
ready: false,
dingtalkStreamState: 'idle',
harnessReachable: false,
lastConnectedAt: null,
lastCheckedAt: null,
lastCallbackAt: null,
authorizationMode: 'sender-staff-id-approval',
approvedSenderCount: approvedSenders,
...createDingtalkBridgeStatus({ pendingSenders }),
};
}
export class DingtalkRuntime {
#config;
#clientSecret;
#harness;
#state;
#logger;
#replyTimeoutMs;
#maxMessageChars;
#connectTimeoutMs;
#connectPollIntervalMs;
#api;
#streamFactory;
#status;
#client = null;
#bridge = null;
#topic = null;
#starting = null;
#connectionMonitor = null;
#abortController = null;
#callbackTasks = new Set();
constructor({
config,
clientSecret,
harness,
state,
logger = console,
replyTimeoutMs = 600_000,
maxMessageChars = 4_000,
connectTimeoutMs = 15_000,
connectPollIntervalMs = 25,
api = createDingtalkApi(),
streamFactory = defaultStreamFactory,
}) {
if (!config || !nonEmptyString(config.clientId) || !nonEmptyString(clientSecret)) {
throw new TypeError('DingtalkRuntime requires app credentials');
}
if (!harness || !state) throw new TypeError('DingtalkRuntime requires Harness and state');
if (typeof streamFactory !== 'function') throw new TypeError('streamFactory must be a function');
this.#config = config;
this.#clientSecret = clientSecret.trim();
this.#harness = harness;
this.#state = state;
this.#logger = logger;
this.#replyTimeoutMs = replyTimeoutMs;
this.#maxMessageChars = maxMessageChars;
this.#connectTimeoutMs = connectTimeoutMs;
this.#connectPollIntervalMs = connectPollIntervalMs;
this.#api = api;
this.#streamFactory = streamFactory;
this.#status = createDingtalkRuntimeStatus({
pendingSenders: this.#pendingSenders(),
approvedSenders: approvedSenderCount(config),
});
}
get status() {
if (this.#bridge) {
const bridgeStatus = this.#bridge.status;
Object.assign(this.#status, bridgeStatus);
} else {
this.#status.pendingSenders = this.#pendingSenders();
}
return structuredClone(this.#status);
}
pendingSender(requestId) {
return typeof this.#state.pendingSender === 'function'
? this.#state.pendingSender(requestId)
: null;
}
pendingSenders() {
return this.#pendingSenders();
}
async start() {
if (this.#client && this.#status.ready) 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();
const abortController = new AbortController();
this.#abortController = abortController;
const { signal } = abortController;
this.#status.startedAt = new Date().toISOString();
this.#status.dingtalkStreamState = 'connecting';
this.#status.lastError = null;
try {
await this.#harness.ensureRunning({ signal });
this.#status.harnessReachable = true;
if (typeof this.#state.removePendingSenderByStaffId === 'function') {
for (const staffId of approvedSenderIds(this.#config)) {
await this.#state.removePendingSenderByStaffId(staffId);
}
this.#status.pendingSenders = this.#pendingSenders();
}
this.#bridge = new DingtalkHarnessBridge({
api: this.#api,
clientId: this.#config.clientId,
clientSecret: this.#clientSecret,
approvedSenders: this.#config.approvedSenders,
harness: this.#harness,
state: this.#state,
status: this.#status,
logger: this.#logger,
replyTimeoutMs: this.#replyTimeoutMs,
maxMessageChars: this.#maxMessageChars,
signal,
});
const created = await this.#streamFactory({
clientId: this.#config.clientId,
clientSecret: this.#clientSecret,
});
signal.throwIfAborted();
this.#client = created?.client ?? created;
this.#topic = created?.topic ?? created?.TOPIC_ROBOT ?? '/v1.0/im/bot/messages/get';
if (!this.#client
|| typeof this.#client.registerCallbackListener !== 'function'
|| typeof this.#client.connect !== 'function'
|| typeof this.#client.disconnect !== 'function'
|| typeof this.#client.socketCallBackResponse !== 'function') {
throw new TypeError('streamFactory returned an invalid DingTalk Stream client');
}
const client = this.#client;
const bridge = this.#bridge;
client.registerCallbackListener(this.#topic, (response) => {
if (this.#client !== client || this.#bridge !== bridge) return;
const callbackMessageId = nonEmptyString(response?.headers?.messageId);
if (callbackMessageId) {
try {
client.socketCallBackResponse(callbackMessageId, { success: true });
} catch {
this.#logger.warn?.('[dsh-dingtalk] unable to acknowledge an inbound callback');
}
}
const task = Promise.resolve().then(async () => {
if (this.#bridge !== bridge) return;
let message;
try {
message = typeof response?.data === 'string'
? JSON.parse(response.data)
: response?.data;
} catch {
this.#status.lastError = '钉钉消息格式无效。';
this.#logger.warn?.('[dsh-dingtalk] ignored an invalid callback payload');
return;
}
if (!message || typeof message !== 'object') return;
this.#status.lastCallbackAt = Date.now();
await bridge.accept(message);
}).catch(() => {
if (signal.aborted || this.#bridge !== bridge) return;
this.#status.lastError = '钉钉消息处理失败。';
this.#logger.error?.('[dsh-dingtalk] callback processing failed');
}).finally(() => this.#callbackTasks.delete(task));
this.#callbackTasks.add(task);
});
await connectStream(
client,
this.#connectTimeoutMs,
this.#connectPollIntervalMs,
signal,
);
this.#status.ready = true;
this.#status.dingtalkStreamState = 'connected';
this.#status.lastConnectedAt = Date.now();
this.#status.lastCheckedAt = Date.now();
this.#status.lastError = null;
this.#connectionMonitor = setInterval(() => {
const connected = streamIsOpen(client);
this.#status.ready = connected;
this.#status.dingtalkStreamState = connected ? 'connected' : 'reconnecting';
this.#status.lastCheckedAt = Date.now();
if (connected) this.#status.lastError = null;
}, 1_000);
this.#connectionMonitor.unref?.();
return this.status;
} catch (error) {
const aborted = signal.aborted;
this.#status.ready = false;
this.#status.dingtalkStreamState = aborted ? 'idle' : 'failed';
this.#status.lastError = aborted ? null : (error?.message ?? String(error));
await this.stop({ preserveError: !aborted });
throw error;
}
}
async stop({ preserveError = false } = {}) {
const lastError = preserveError ? this.#status.lastError : null;
const abortController = this.#abortController;
this.#abortController = null;
abortController?.abort(new DOMException('DingTalk runtime stopped', 'AbortError'));
if (this.#connectionMonitor) clearInterval(this.#connectionMonitor);
this.#connectionMonitor = null;
this.#status.ready = false;
const client = this.#client;
this.#client = null;
this.#topic = null;
if (client) {
try {
await client.disconnect();
} catch {
this.#logger.warn?.('[dsh-dingtalk] DingTalk Stream disconnect failed');
}
}
await Promise.allSettled([...this.#callbackTasks]);
this.#callbackTasks.clear();
if (this.#bridge) await this.#bridge.waitForIdle();
this.#bridge = null;
this.#status.dingtalkStreamState = preserveError ? 'failed' : 'idle';
this.#status.lastError = lastError;
return this.status;
}
#pendingSenders() {
return typeof this.#state.pendingSenders === 'function'
? this.#state.pendingSenders()
: [];
}
}
export const DingTalkRuntime = DingtalkRuntime;
export const createDingTalkRuntimeStatus = createDingtalkRuntimeStatus;

View file

@ -0,0 +1,299 @@
import { spawn } from 'node:child_process';
import { randomUUID } from 'node:crypto';
function sleep(ms, signal) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
return;
}
const timer = setTimeout(() => {
signal?.removeEventListener('abort', onAbort);
resolve();
}, ms);
const onAbort = () => {
clearTimeout(timer);
reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
};
signal?.addEventListener('abort', onAbort, { once: true });
});
}
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;
#fetch;
#managedProcess = null;
constructor({
baseUrl,
workspace,
agentPreset = 'standard',
autostart = false,
dshBin = 'dsh',
fetchImpl = fetch,
}) {
this.#baseUrl = new URL(baseUrl);
this.#workspace = workspace;
this.#agentPreset = agentPreset;
this.#autostart = autostart;
this.#dshBin = dshBin;
this.#fetch = fetchImpl;
}
async rpc(method, payload = {}, timeoutMs = 30_000, options = {}) {
const rpcId = options.rpcId ?? `dingtalk-${randomUUID()}`;
const timeoutSignal = AbortSignal.timeout(timeoutMs);
const signal = options.signal
? AbortSignal.any([options.signal, timeoutSignal])
: timeoutSignal;
const response = await this.#fetch(new URL(`/api/${method}`, this.#baseUrl), {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ type: 'client-request', rpcId, method, payload }),
signal,
});
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(options = {}) {
await this.rpc('host.describe', {}, 5_000, options);
return true;
}
async ensureRunning(options = {}) {
try {
return await this.health(options);
} 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-dingtalk] failed to start Harness:', error.message);
});
}
const deadline = Date.now() + 60_000;
let lastError;
while (Date.now() < deadline) {
await sleep(1_000, options.signal);
try {
return await this.health(options);
} catch (error) {
lastError = error;
}
}
throw new Error(`Harness did not become ready: ${lastError?.message ?? 'timeout'}`);
}
async workspaceId(options = {}) {
const { items } = await this.rpc('workspace.list', {}, 30_000, options);
const existing = items.find((item) => item.path === this.#workspace);
if (existing) return existing.workspaceId;
const created = await this.rpc('workspace.create', { path: this.#workspace }, 30_000, options);
return created.workspace.workspaceId;
}
async createSession(options = {}) {
await this.ensureRunning(options);
const workspaceId = await this.workspaceId(options);
const created = await this.rpc('session.create', {
workspaceId,
agentPreset: this.#agentPreset,
}, 30_000, options);
return created.sessionId;
}
async sessionExists(sessionId, options = {}) {
try {
await this.rpc('session.history', { sessionId, maxMessages: 1 }, 30_000, options);
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 signal = options.signal;
const onUpdate = typeof options.onUpdate === 'function' ? options.onUpdate : null;
await this.ensureRunning({ signal });
const before = await this.rpc(
'session.history',
{ sessionId, maxMessages: 1 },
30_000,
{ signal },
);
const baselineSeq = Math.max(-1, ...(before.events ?? []).map(({ event }) => event.seq ?? -1));
const promptRpcId = `dingtalk-${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, signal });
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
await sleep(300, signal);
const history = await this.rpc(
'session.history',
{ sessionId, maxMessages: 50 },
30_000,
{ signal },
);
const update = tracker.consume(history.events ?? []);
if (update && onUpdate) {
try {
await onUpdate(update);
} catch (error) {
console.warn('[dsh-dingtalk] 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,212 @@
import { randomUUID } from 'node:crypto';
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
const EMPTY_STATE = Object.freeze({
version: 1,
sessions: {},
seenMessageIds: [],
pendingSenders: {},
});
function nonEmptyString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function displayName(value) {
return (nonEmptyString(value) ?? '钉钉用户').slice(0, 100);
}
function normalizePendingSender(value, fallbackRequestId) {
if (!value || typeof value !== 'object') return null;
const requestId = nonEmptyString(value.requestId) ?? nonEmptyString(fallbackRequestId);
const staffId = nonEmptyString(value.staffId);
const requestedAt = nonEmptyString(value.requestedAt) ?? nonEmptyString(value.lastSeenAt);
const lastSeenAt = nonEmptyString(value.lastSeenAt) ?? requestedAt;
if (!requestId || !staffId || !requestedAt || !lastSeenAt) return null;
return {
requestId,
staffId,
displayName: displayName(value.displayName ?? value.nick),
requestedAt,
lastSeenAt,
};
}
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)) {
const normalizedKey = nonEmptyString(key);
const normalizedSession = nonEmptyString(sessionId);
if (normalizedKey && normalizedSession) sessions[normalizedKey] = normalizedSession;
}
}
const pendingSenders = {};
const entries = Array.isArray(value.pendingSenders)
? value.pendingSenders.map((entry) => [entry?.requestId, entry])
: Object.entries(value.pendingSenders && typeof value.pendingSenders === 'object'
? value.pendingSenders
: {});
for (const [key, candidate] of entries) {
const pending = normalizePendingSender(candidate, key);
if (!pending) continue;
const duplicate = Object.values(pendingSenders).find((entry) => entry.staffId === pending.staffId);
if (!duplicate || duplicate.lastSeenAt < pending.lastSeenAt) {
if (duplicate) delete pendingSenders[duplicate.requestId];
pendingSenders[pending.requestId] = pending;
}
}
return {
version: 1,
sessions,
seenMessageIds: Array.isArray(value.seenMessageIds)
? [...new Set(value.seenMessageIds.map(nonEmptyString).filter(Boolean))].slice(-1_000)
: [],
pendingSenders,
};
}
export class DingtalkStateStore {
#path;
#state = structuredClone(EMPTY_STATE);
#writeQueue = Promise.resolve();
#idFactory;
#now;
constructor(path, { idFactory = randomUUID, now = () => new Date().toISOString() } = {}) {
if (!nonEmptyString(path)) throw new TypeError('state path is required');
if (typeof idFactory !== 'function' || typeof now !== 'function') {
throw new TypeError('idFactory and now must be functions');
}
this.#path = path;
this.#idFactory = idFactory;
this.#now = now;
}
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) {
const normalizedKey = nonEmptyString(key);
const normalizedSession = nonEmptyString(sessionId);
if (!normalizedKey || !normalizedSession) throw new TypeError('key and sessionId are required');
this.#state.sessions[normalizedKey] = normalizedSession;
await this.#persist();
}
async clearSession(key) {
const normalizedKey = nonEmptyString(key);
if (!normalizedKey || !(normalizedKey in this.#state.sessions)) return;
delete this.#state.sessions[normalizedKey];
await this.#persist();
}
hasSeen(messageId) {
const id = nonEmptyString(messageId);
return Boolean(id && this.#state.seenMessageIds.includes(id));
}
async markSeen(messageId) {
const id = nonEmptyString(messageId);
if (!id) throw new TypeError('messageId is required');
if (this.hasSeen(id)) return;
this.#state.seenMessageIds.push(id);
if (this.#state.seenMessageIds.length > 1_000) {
this.#state.seenMessageIds.splice(0, this.#state.seenMessageIds.length - 1_000);
}
await this.#persist();
}
pendingSenders() {
return Object.values(this.#state.pendingSenders)
.sort((left, right) => left.requestedAt.localeCompare(right.requestedAt))
.map((entry) => structuredClone(entry));
}
pendingSender(requestId) {
const id = nonEmptyString(requestId);
const entry = id ? this.#state.pendingSenders[id] : null;
return entry ? structuredClone(entry) : null;
}
async recordPendingSender(staffIdOrEntry, name, seenAt) {
const input = staffIdOrEntry && typeof staffIdOrEntry === 'object'
? staffIdOrEntry
: { staffId: staffIdOrEntry, displayName: name, lastSeenAt: seenAt };
const staffId = nonEmptyString(input.staffId);
if (!staffId) throw new TypeError('staffId is required');
const timestamp = nonEmptyString(input.lastSeenAt) ?? nonEmptyString(input.requestedAt) ?? this.#now();
const existing = Object.values(this.#state.pendingSenders)
.find((entry) => entry.staffId === staffId);
const entry = {
requestId: existing?.requestId ?? `ding_sender_${this.#idFactory()}`,
staffId,
displayName: displayName(input.displayName ?? input.nick ?? name),
requestedAt: existing?.requestedAt ?? timestamp,
lastSeenAt: timestamp,
};
this.#state.pendingSenders[entry.requestId] = entry;
await this.#persist();
return structuredClone(entry);
}
async removePendingSender(requestId) {
const id = nonEmptyString(requestId);
if (!id || !this.#state.pendingSenders[id]) return false;
delete this.#state.pendingSenders[id];
await this.#persist();
return true;
}
async removePendingSenderByStaffId(staffId) {
const id = nonEmptyString(staffId);
const pending = id
? Object.values(this.#state.pendingSenders).find((entry) => entry.staffId === id)
: null;
return pending ? this.removePendingSender(pending.requestId) : false;
}
snapshot() {
return structuredClone(this.#state);
}
async remove() {
await this.#writeQueue;
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;
}
}
export const DingTalkStateStore = DingtalkStateStore;

View file

@ -0,0 +1,216 @@
import {
conversationKey,
extractText,
isAllowedSender,
isBotSender,
splitText,
} from './message-utils.mjs';
const HELP_TEXT = [
'北汇星河 AIOS 已连接 DeepSeek Harness。',
'',
'直接发送问题即可继续当前会话。',
'/new 开启一个全新会话',
'/status 检查连接状态',
'/help 显示本帮助',
].join('\n');
export class FeishuHarnessBridge {
#client;
#channel;
#harness;
#state;
#queues = new Map();
#acceptedMessageIds = new Set();
#status;
#allowedSenderOpenIds;
#replyTimeoutMs;
constructor({
client,
channel,
harness,
state,
status,
allowedSenderOpenIds = new Set(),
replyTimeoutMs = 600000,
}) {
this.#client = client;
this.#channel = channel;
this.#harness = harness;
this.#state = state;
this.#status = status;
this.#allowedSenderOpenIds = allowedSenderOpenIds;
this.#replyTimeoutMs = replyTimeoutMs;
}
accept(event) {
const messageId = event?.message?.message_id;
if (!messageId || isBotSender(event) || event?.message?.message_type !== 'text') return;
if (!isAllowedSender(event, this.#allowedSenderOpenIds)) {
this.#status.messagesRejected += 1;
this.#status.lastRejectedAt = new Date().toISOString();
console.warn('[bridge] ignored a message from a sender outside the allowlist');
return;
}
if (this.#state.hasSeen(messageId) || this.#acceptedMessageIds.has(messageId)) return;
this.#acceptedMessageIds.add(messageId);
const processingReaction = this.#addReaction(messageId, 'OnIt');
const key = conversationKey(event);
const previous = this.#queues.get(key) ?? Promise.resolve();
const task = previous
.catch(() => undefined)
.then(() => this.#handle(event, key))
.then(() => this.#finishReaction(messageId, processingReaction, 'DONE'))
.catch(async (error) => {
console.error('[bridge] message handling failed:', error.message);
this.#status.lastError = error.message;
await this.#finishReaction(messageId, processingReaction, 'ERROR');
await this.#send(
event.message.chat_id,
'处理失败,请稍后重试。如果问题持续,请在 DeepSeek Harness 的飞书插件页面检查连接状态。',
).catch(() => undefined);
})
.finally(() => {
this.#acceptedMessageIds.delete(messageId);
if (this.#queues.get(key) === task) this.#queues.delete(key);
});
this.#queues.set(key, task);
}
async waitForIdle() {
await Promise.allSettled([...this.#queues.values()]);
}
async #handle(event, key) {
const messageId = event.message.message_id;
await this.#state.markSeen(messageId);
this.#status.lastMessageAt = new Date().toISOString();
this.#status.messagesReceived += 1;
const text = extractText(event);
if (!text) return;
if (text === '/help') {
await this.#send(event.message.chat_id, HELP_TEXT);
return;
}
if (text === '/new') {
await this.#state.clearSession(key);
await this.#send(event.message.chat_id, '已开启全新 Harness 会话。');
return;
}
if (text === '/status') {
await this.#harness.ensureRunning();
await this.#send(event.message.chat_id, '飞书机器人与 DeepSeek Harness 连接正常。');
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);
}
console.info(`[bridge] processing ${event.message.chat_type} message ${messageId} in ${sessionId}`);
await this.#answerWithStream(event, sessionId, text);
this.#status.messagesReplied += 1;
this.#status.lastReplyAt = new Date().toISOString();
this.#status.lastError = null;
}
async #answerWithStream(event, sessionId, text) {
const chatId = event.message.chat_id;
const messageId = event.message.message_id;
if (!this.#channel?.stream) {
const answer = await this.#harness.ask(sessionId, text, { timeoutMs: this.#replyTimeoutMs });
for (const chunk of splitText(answer)) await this.#send(chatId, chunk);
this.#status.streamFallbacks = (this.#status.streamFallbacks ?? 0) + 1;
return;
}
let promptStarted = false;
let completedAnswer = '';
try {
await this.#channel.stream(chatId, {
markdown: async (controller) => {
promptStarted = true;
completedAnswer = await this.#harness.ask(sessionId, text, {
timeoutMs: this.#replyTimeoutMs,
onUpdate: async (update) => {
await controller.setContent(this.#progressText(update));
this.#status.streamUpdates = (this.#status.streamUpdates ?? 0) + 1;
},
});
await controller.setContent(completedAnswer);
},
}, { replyTo: messageId });
this.#status.streamResponses = (this.#status.streamResponses ?? 0) + 1;
} catch (error) {
this.#status.streamErrors = (this.#status.streamErrors ?? 0) + 1;
if (completedAnswer) {
console.warn('[bridge] native Feishu stream failed after generation; sending final text:', error.message);
for (const chunk of splitText(completedAnswer)) await this.#send(chatId, chunk);
this.#status.streamFallbacks = (this.#status.streamFallbacks ?? 0) + 1;
return;
}
if (promptStarted) throw error;
console.warn('[bridge] native Feishu stream unavailable; using text fallback:', error.message);
const answer = await this.#harness.ask(sessionId, text, { timeoutMs: this.#replyTimeoutMs });
for (const chunk of splitText(answer)) await this.#send(chatId, chunk);
this.#status.streamFallbacks = (this.#status.streamFallbacks ?? 0) + 1;
}
}
#progressText(update) {
if (update.type === 'text' && update.text) return update.text;
if (update.type === 'tool') {
if (update.name === 'web_search') return '_正在搜索网络并整理信息…_';
return `_正在使用 ${update.name || '工具'}…_`;
}
return `_${update.text || '正在处理…'}_`;
}
async #addReaction(messageId, emojiType) {
if (!this.#channel?.addReaction) return null;
try {
const reactionId = await this.#channel.addReaction(messageId, emojiType);
this.#status.reactionsAdded = (this.#status.reactionsAdded ?? 0) + 1;
return reactionId;
} catch (error) {
this.#status.reactionErrors = (this.#status.reactionErrors ?? 0) + 1;
console.warn(`[bridge] unable to add ${emojiType} reaction:`, error.message);
return null;
}
}
async #finishReaction(messageId, processingReaction, finalEmojiType) {
const reactionId = await processingReaction;
if (reactionId && this.#channel?.removeReaction) {
try {
await this.#channel.removeReaction(messageId, reactionId);
this.#status.reactionsRemoved = (this.#status.reactionsRemoved ?? 0) + 1;
} catch (error) {
this.#status.reactionErrors = (this.#status.reactionErrors ?? 0) + 1;
console.warn('[bridge] unable to remove processing reaction:', error.message);
}
}
await this.#addReaction(messageId, finalEmojiType);
}
async #send(chatId, text) {
const response = await this.#client.im.v1.message.create({
params: { receive_id_type: 'chat_id' },
data: {
receive_id: chatId,
msg_type: 'text',
content: JSON.stringify({ text }),
},
});
if (response?.code && response.code !== 0) {
throw new Error(`Feishu send failed: ${response.msg || response.code}`);
}
}
}

View file

@ -0,0 +1,71 @@
import { execFileSync } from 'node:child_process';
import { resolve } from 'node:path';
function required(name, value) {
if (typeof value !== 'string' || value.trim() === '') {
throw new Error(`Missing required configuration: ${name}`);
}
return value.trim();
}
function readSecret(appId) {
if (process.env.FEISHU_APP_SECRET?.trim()) return process.env.FEISHU_APP_SECRET.trim();
const service = process.env.FEISHU_SECRET_SERVICE?.trim();
if (!service) throw new Error('Missing FEISHU_APP_SECRET or FEISHU_SECRET_SERVICE');
try {
return execFileSync('/usr/bin/security', [
'find-generic-password',
'-a',
appId,
'-s',
service,
'-w',
], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
} catch {
throw new Error(`Unable to read Feishu app secret from macOS Keychain service ${service}`);
}
}
function bool(name, fallback) {
const raw = process.env[name];
if (raw === undefined) return fallback;
return !['0', 'false', 'no', 'off'].includes(raw.trim().toLowerCase());
}
function csvSet(value) {
return new Set((value ?? '')
.split(',')
.map((item) => item.trim())
.filter(Boolean));
}
function requiredCsvSet(name, value) {
const items = csvSet(value);
if (items.size === 0) throw new Error(`Missing required configuration: ${name}`);
return items;
}
export function loadConfig() {
const appId = required('FEISHU_APP_ID', process.env.FEISHU_APP_ID);
const appSecret = required('FEISHU_APP_SECRET', readSecret(appId));
const workspace = required('HARNESS_WORKSPACE', process.env.HARNESS_WORKSPACE);
return Object.freeze({
appId,
appSecret,
harnessBaseUrl: new URL(process.env.HARNESS_BASE_URL ?? 'http://127.0.0.1:3080'),
harnessWorkspace: resolve(workspace),
harnessAgentPreset: process.env.HARNESS_AGENT_PRESET?.trim() || 'standard',
harnessAutostart: bool('HARNESS_AUTOSTART', true),
dshBin: process.env.DSH_BIN?.trim() || 'dsh',
healthPort: Number.parseInt(process.env.BRIDGE_HEALTH_PORT ?? '3091', 10),
statePath: resolve(process.env.BRIDGE_STATE_PATH ?? './data/state.json'),
replyTimeoutMs: Number.parseInt(process.env.HARNESS_REPLY_TIMEOUT_MS ?? '600000', 10),
allowedSenderOpenIds: requiredCsvSet(
'FEISHU_ALLOWED_OPEN_IDS',
process.env.FEISHU_ALLOWED_OPEN_IDS,
),
});
}

View file

@ -0,0 +1,51 @@
function endpointFor(domain, path) {
const origin = domain === 'lark' ? 'https://open.larksuite.com' : 'https://open.feishu.cn';
return new URL(path, origin);
}
async function jsonResponse(response, operation) {
let body;
try {
body = await response.json();
} catch {
throw new Error(`${operation} returned a non-JSON response`);
}
if (!response.ok || body?.code !== 0) {
throw new Error(`${operation} failed: ${body?.msg || `HTTP ${response.status}`}`);
}
return body;
}
/** Validate freshly provisioned credentials and read the bot identity. */
export async function verifyFeishuApp({
appId,
appSecret,
domain = 'feishu',
fetchImpl = fetch,
timeoutMs = 15000,
}) {
if (!appId || !appSecret) throw new Error('Feishu credentials are incomplete');
const tokenResponse = await fetchImpl(endpointFor(domain, '/open-apis/auth/v3/tenant_access_token/internal'), {
method: 'POST',
headers: { 'content-type': 'application/json; charset=utf-8' },
body: JSON.stringify({ app_id: appId, app_secret: appSecret }),
signal: AbortSignal.timeout(timeoutMs),
});
const tokenBody = await jsonResponse(tokenResponse, 'Feishu authentication');
if (!tokenBody.tenant_access_token) {
throw new Error('Feishu authentication returned no tenant access token');
}
const botResponse = await fetchImpl(endpointFor(domain, '/open-apis/bot/v3/info/'), {
headers: { authorization: `Bearer ${tokenBody.tenant_access_token}` },
signal: AbortSignal.timeout(timeoutMs),
});
const botBody = await jsonResponse(botResponse, 'Feishu bot verification');
const bot = botBody.bot ?? {};
return Object.freeze({
appId,
name: bot.app_name ?? bot.bot_name ?? null,
openId: bot.open_id ?? null,
activated: bot.activate_status ?? null,
});
}

View file

@ -0,0 +1,153 @@
const STREAM_ELEMENT_ID = 'stream_md';
const DEFAULT_INITIAL_TEXT = '已连接 DeepSeek Harness,正在思考…';
const MAX_STREAM_CHARS = 28000;
function assertApiSuccess(operation, response) {
if (response?.code && response.code !== 0) {
throw new Error(`${operation} failed: ${response.msg || response.code}`);
}
return response;
}
function summaryOf(text) {
const summary = String(text ?? '').replace(/\s+/g, ' ').trim();
return summary.length <= 50 ? summary : `${summary.slice(0, 49)}…`;
}
function streamingCard(initialText) {
return {
schema: '2.0',
config: {
streaming_mode: true,
summary: { content: '正在生成…' },
streaming_config: {
print_frequency_ms: { default: 70 },
print_step: { default: 1 },
print_strategy: 'fast',
},
},
body: {
elements: [{
tag: 'markdown',
element_id: STREAM_ELEMENT_ID,
content: initialText,
}],
},
};
}
export class VerifiedFeishuChannel {
#client;
#initialText;
constructor({ client, initialText = DEFAULT_INITIAL_TEXT }) {
this.#client = client;
this.#initialText = initialText;
}
async stream(chatId, input, options = {}) {
if (typeof input?.markdown !== 'function') {
throw new Error('Feishu stream requires a markdown producer');
}
let messageId = null;
const cardResponse = assertApiSuccess('Feishu card.create', await this.#client.cardkit.v1.card.create({
data: {
type: 'card_json',
data: JSON.stringify(streamingCard(this.#initialText)),
},
}));
const cardId = cardResponse?.data?.card_id;
if (!cardId) throw new Error('Feishu card.create returned no card_id');
try {
messageId = await this.#sendCard(chatId, cardId, options.replyTo);
let sequence = 0;
let lastContent = this.#initialText;
const controller = {
messageId,
setContent: async (content) => {
const next = String(content ?? '') || '…';
if (next === lastContent) return;
if (next.length > MAX_STREAM_CHARS) {
throw new Error(`Feishu stream content exceeds ${MAX_STREAM_CHARS} characters`);
}
const response = await this.#client.cardkit.v1.cardElement.content({
path: { card_id: cardId, element_id: STREAM_ELEMENT_ID },
data: {
content: next,
sequence: ++sequence,
uuid: `content_${cardId}_${sequence}`,
},
});
assertApiSuccess('Feishu cardElement.content', response);
lastContent = next;
},
};
await input.markdown(controller);
const finishResponse = await this.#client.cardkit.v1.card.settings({
path: { card_id: cardId },
data: {
settings: JSON.stringify({
config: {
streaming_mode: false,
summary: { content: summaryOf(lastContent) || '回答完成' },
},
}),
sequence: ++sequence,
uuid: `settings_${cardId}_${sequence}`,
},
});
assertApiSuccess('Feishu card.settings', finishResponse);
return { messageId };
} catch (error) {
if (messageId) await this.#recall(messageId);
throw error;
}
}
async #sendCard(chatId, cardId, replyTo) {
const content = JSON.stringify({ type: 'card', data: { card_id: cardId } });
const response = replyTo
? await this.#client.im.v1.message.reply({
path: { message_id: replyTo },
data: { msg_type: 'interactive', content },
})
: await this.#client.im.v1.message.create({
params: { receive_id_type: 'chat_id' },
data: { receive_id: chatId, msg_type: 'interactive', content },
});
assertApiSuccess('Feishu message send', response);
const messageId = response?.data?.message_id;
if (!messageId) throw new Error('Feishu message send returned no message_id');
return messageId;
}
async #recall(messageId) {
try {
const response = await this.#client.im.v1.message.delete({
path: { message_id: messageId },
});
assertApiSuccess('Feishu message delete', response);
} catch (error) {
console.warn('[bridge] unable to recall a failed streaming card:', error.message);
}
}
async addReaction(messageId, emojiType) {
const response = assertApiSuccess('Feishu reaction.create', await this.#client.im.v1.messageReaction.create({
path: { message_id: messageId },
data: { reaction_type: { emoji_type: emojiType } },
}));
const reactionId = response?.data?.reaction_id;
if (!reactionId) throw new Error('Feishu reaction.create returned no reaction_id');
return reactionId;
}
async removeReaction(messageId, reactionId) {
assertApiSuccess('Feishu reaction.delete', await this.#client.im.v1.messageReaction.delete({
path: { message_id: messageId, reaction_id: reactionId },
}));
}
}

View file

@ -0,0 +1,222 @@
import { FeishuHarnessBridge } from './bridge.mjs';
import { VerifiedFeishuChannel } from './feishu-channel.mjs';
export function createBridgeStatus({ allowedSenderCount = 1 } = {}) {
return {
startedAt: null,
ready: false,
feishuLongConnectionState: 'idle',
harnessReachable: false,
messagesReceived: 0,
messagesReplied: 0,
messagesRejected: 0,
reactionsAdded: 0,
reactionsRemoved: 0,
reactionErrors: 0,
streamResponses: 0,
streamUpdates: 0,
streamFallbacks: 0,
streamErrors: 0,
lastMessageAt: null,
lastReplyAt: null,
lastRejectedAt: null,
lastError: null,
agentPreset: 'standard',
authorizationMode: 'sender-open-id-allowlist',
allowedSenderCount,
};
}
/**
* Owns one live Feishu long connection and the already-tested bridge stack.
* The class intentionally receives the SDK and Harness dependencies so the
* plugin can run it in-process while tests exercise the lifecycle without a
* real Feishu tenant.
*/
export class FeishuRuntime {
#lark;
#appId;
#appSecret;
#domain;
#ownerOpenIds;
#harness;
#state;
#replyTimeoutMs;
#connectTimeoutMs;
#logger;
#client = null;
#bridge = null;
#wsClient = null;
#starting = null;
#status;
constructor({
lark,
appId,
appSecret,
domain = 'feishu',
ownerOpenId,
ownerOpenIds,
harness,
state,
replyTimeoutMs = 600000,
connectTimeoutMs = 15000,
logger = console,
}) {
if (!lark) throw new Error('FeishuRuntime requires the Feishu SDK');
if (!appId || !appSecret) throw new Error('FeishuRuntime requires app credentials');
const allowedOwners = Array.isArray(ownerOpenIds) ? ownerOpenIds : [ownerOpenId];
const normalizedOwners = [...new Set(allowedOwners.filter((value) => typeof value === 'string' && value))];
if (normalizedOwners.length === 0) throw new Error('FeishuRuntime requires at least one owner open_id');
if (!harness) throw new Error('FeishuRuntime requires a Harness client');
if (!state) throw new Error('FeishuRuntime requires a state store');
this.#lark = lark;
this.#appId = appId;
this.#appSecret = appSecret;
this.#domain = domain;
this.#ownerOpenIds = normalizedOwners;
this.#harness = harness;
this.#state = state;
this.#replyTimeoutMs = replyTimeoutMs;
this.#connectTimeoutMs = connectTimeoutMs;
this.#logger = logger;
this.#status = createBridgeStatus({ allowedSenderCount: normalizedOwners.length });
}
get status() {
return structuredClone(this.#status);
}
async start() {
if (this.#wsClient && this.#status.ready) return this.status;
if (this.#starting) return this.#starting;
this.#starting = this.#start().finally(() => {
this.#starting = null;
});
return this.#starting;
}
async #start() {
this.#status.startedAt = new Date().toISOString();
this.#status.feishuLongConnectionState = 'connecting';
this.#status.lastError = null;
try {
await this.#harness.ensureRunning();
this.#status.harnessReachable = true;
const sdkDomain = this.#domain === 'lark'
? this.#lark.Domain.Lark
: this.#lark.Domain.Feishu;
const larkConfig = {
appId: this.#appId,
appSecret: this.#appSecret,
domain: sdkDomain,
};
this.#client = new this.#lark.Client(larkConfig);
const channel = new VerifiedFeishuChannel({
client: this.#client,
initialText: '已连接 DeepSeek Harness,正在思考…',
});
this.#bridge = new FeishuHarnessBridge({
client: this.#client,
channel,
harness: this.#harness,
state: this.#state,
status: this.#status,
allowedSenderOpenIds: new Set(this.#ownerOpenIds),
replyTimeoutMs: this.#replyTimeoutMs,
});
const dispatcher = new this.#lark.EventDispatcher({}).register({
'im.message.receive_v1': (event) => {
this.#bridge.accept(event);
return {};
},
'im.message.reaction.created_v1': () => ({}),
'im.message.reaction.deleted_v1': () => ({}),
});
let settleReady;
let settleError;
const ready = new Promise((resolve, reject) => {
let settled = false;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
reject(new Error(`Feishu WebSocket handshake timed out after ${this.#connectTimeoutMs}ms`));
}, this.#connectTimeoutMs);
settleReady = () => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve();
};
settleError = (error) => {
if (settled) return;
settled = true;
clearTimeout(timer);
reject(error);
};
});
this.#wsClient = new this.#lark.WSClient({
...larkConfig,
loggerLevel: this.#lark.LoggerLevel.info,
handshakeTimeoutMs: 15000,
onReady: () => {
this.#status.feishuLongConnectionState = 'connected';
this.#status.ready = true;
this.#status.lastError = null;
settleReady();
},
onError: (error) => {
this.#status.feishuLongConnectionState = 'failed';
this.#status.ready = false;
this.#status.lastError = error?.message ?? String(error);
this.#logger.error('[dsh-feishu] Feishu long connection failed:', this.#status.lastError);
settleError(error);
},
onReconnecting: () => {
this.#status.feishuLongConnectionState = 'reconnecting';
this.#status.ready = false;
},
onReconnected: () => {
this.#status.feishuLongConnectionState = 'connected';
this.#status.ready = true;
this.#status.lastError = null;
},
});
await this.#wsClient.start({ eventDispatcher: dispatcher }).catch((error) => {
settleError(error);
});
await ready;
return this.status;
} catch (error) {
this.#status.ready = false;
this.#status.feishuLongConnectionState = 'failed';
this.#status.lastError = error?.message ?? String(error);
await this.stop({ preserveError: true });
throw error;
}
}
async stop({ preserveError = false } = {}) {
const error = preserveError ? this.#status.lastError : null;
this.#status.ready = false;
if (this.#wsClient) {
this.#wsClient.close({ force: true });
this.#wsClient = null;
}
if (this.#bridge) {
await this.#bridge.waitForIdle();
this.#bridge = null;
}
this.#client = null;
this.#status.feishuLongConnectionState = preserveError ? 'failed' : 'idle';
this.#status.lastError = error;
return this.status;
}
}

View file

@ -0,0 +1,268 @@
import { spawn } from 'node:child_process';
import { randomUUID } from 'node:crypto';
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function messageText(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 stepPrefix = `${step}:`;
const text = [...this.#stepText.entries()]
.filter(([partKey]) => partKey.startsWith(stepPrefix))
.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 = messageText(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, autostart, dshBin }) {
this.#baseUrl = new URL(baseUrl);
this.#workspace = workspace;
this.#agentPreset = agentPreset;
this.#autostart = autostart;
this.#dshBin = dshBin;
}
async rpc(method, payload = {}, timeoutMs = 30000, options = {}) {
const rpcId = options.rpcId ?? `feishu-${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', {}, 5000);
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('[bridge] failed to start Harness:', error.message);
});
}
const deadline = Date.now() + 60000;
let lastError;
while (Date.now() < deadline) {
await sleep(1000);
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 ?? 600000;
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 = `feishu-${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,
}, 30000, { 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('[bridge] 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 / 1000)} seconds`);
}
stopManagedProcess() {
if (this.#managedProcess?.exitCode === null) this.#managedProcess.kill('SIGTERM');
}
}

View file

@ -0,0 +1,50 @@
export function conversationKey(event) {
const chatType = event?.message?.chat_type;
if (chatType === 'p2p') {
const senderId = event?.sender?.sender_id?.open_id || event?.sender?.sender_id?.user_id;
if (!senderId) throw new Error('Feishu p2p event has no sender id');
return `p2p:${senderId}`;
}
const chatId = event?.message?.chat_id;
if (!chatId) throw new Error('Feishu group event has no chat id');
return `group:${chatId}`;
}
export function extractText(event) {
if (event?.message?.message_type !== 'text') return null;
let parsed;
try {
parsed = JSON.parse(event.message.content);
} catch {
return null;
}
let text = typeof parsed.text === 'string' ? parsed.text : '';
for (const mention of event.message.mentions ?? []) {
if (typeof mention.key === 'string' && mention.key) text = text.replaceAll(mention.key, '');
}
return text.trim();
}
export function splitText(text, maxChars = 9000) {
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;
}
export function isBotSender(event) {
return event?.sender?.sender_type === 'bot';
}
export function isAllowedSender(event, allowedOpenIds) {
if (!allowedOpenIds || allowedOpenIds.size === 0) return false;
const senderOpenId = event?.sender?.sender_id?.open_id;
return typeof senderOpenId === 'string' && allowedOpenIds.has(senderOpenId);
}

View file

@ -0,0 +1,616 @@
import { randomUUID } from 'node:crypto';
import { RegistrationManager } from './registration-manager.mjs';
import { REQUIRED_TENANT_SCOPES } from './plugin-controller.mjs';
const ACTIVE_REGISTRATION_STATES = new Set([
'starting', 'qr_ready', 'polling', 'slow_down', 'domain_switched',
]);
const MUTABLE_REGISTRATION_STATES = new Set([...ACTIVE_REGISTRATION_STATES, 'saving']);
function idleConnection() {
return {
ready: false,
feishuLongConnectionState: 'idle',
harnessReachable: false,
};
}
function connectionStatus(runtime) {
return runtime ? runtime.status : idleConnection();
}
function isConnected(connection) {
return connection.ready === true
&& connection.feishuLongConnectionState === 'connected'
&& connection.harnessReachable === true;
}
function maskedAppId(appId) {
return appId.length > 12
? `${appId.slice(0, 8)}••••${appId.slice(-4)}`
: 'cli_••••';
}
function publicBot(config) {
return {
name: config.botName,
appIdMasked: maskedAppId(config.appId),
activated: config.activated,
domain: config.domain,
};
}
function botPhase({ connected, error, connection }) {
if (connected) return 'connected';
if (error || connection.feishuLongConnectionState === 'failed') return 'error';
return 'disconnected';
}
function makeBotId() {
return `bot_${randomUUID().replaceAll('-', '')}`;
}
function makeRegistrationId() {
return `reg_${randomUUID().replaceAll('-', '')}`;
}
function secretRefFor(botId) {
return `DSH_FEISHU_APP_SECRET_${botId.slice(4).toUpperCase()}`;
}
/**
* Multi-account Feishu orchestration. Each bot owns its credential reference,
* runtime and session store. Config commits are serialized, while unrelated
* runtime lifecycles may proceed independently.
*/
export class MultiBotDshFeishuController {
#registerApp;
#verifyApp;
#credentials;
#configStore;
#createRuntime;
#deleteState;
#createBotId;
#createRegistrationId;
#runtimes = new Map();
#botErrors = new Map();
#registrations = new Map();
#botOwnership = new Map();
#latestRegistrationId = null;
#configTransition = Promise.resolve();
#botTransitions = new Map();
#revision = 1;
#closed = false;
constructor({
registerApp,
verifyApp,
credentials,
configStore,
createRuntime,
deleteState = async () => {},
createBotId = makeBotId,
createRegistrationId = makeRegistrationId,
}) {
if (typeof registerApp !== 'function') throw new Error('registerApp is required');
if (typeof verifyApp !== 'function') throw new Error('verifyApp is required');
if (!credentials) throw new Error('credentials service is required');
if (!configStore || typeof configStore.list !== 'function') {
throw new Error('multi-bot config store is required');
}
if (typeof createRuntime !== 'function') throw new Error('createRuntime is required');
if (typeof deleteState !== 'function') throw new Error('deleteState must be a function');
this.#registerApp = registerApp;
this.#verifyApp = verifyApp;
this.#credentials = credentials;
this.#configStore = configStore;
this.#createRuntime = createRuntime;
this.#deleteState = deleteState;
this.#createBotId = createBotId;
this.#createRegistrationId = createRegistrationId;
}
async initialize() {
if (this.#closed) return this.status();
const bots = this.#configStore.list();
let attempted = false;
await Promise.allSettled(bots.map((config) => this.#withBotTransition(config.id, async () => {
const current = connectionStatus(this.#runtimes.get(config.id));
if (isConnected(current)
|| current.feishuLongConnectionState === 'connecting'
|| current.feishuLongConnectionState === 'reconnecting') {
return;
}
attempted = true;
if (config.deletionPending) {
this.#botErrors.set(config.id, {
code: 'deletion_pending',
message: '机器人正在等待完成本地删除,请重试移除。',
});
return;
}
let resolved;
try {
resolved = await this.#credentials.resolve(config.secretRef);
} catch {
this.#botErrors.set(config.id, {
code: 'missing_credentials',
message: '无法读取机器人凭据,请检查凭据存储。',
});
return;
}
if (!resolved?.value) {
this.#botErrors.set(config.id, {
code: 'missing_credentials',
message: '机器人凭据缺失,请删除后重新扫码接入。',
});
return;
}
try {
await this.#startRuntime(config, resolved.value);
this.#botErrors.delete(config.id);
} catch {
this.#botErrors.set(config.id, {
code: 'connection_failed',
message: '机器人暂时无法连接飞书,请重试。',
});
}
})));
if (attempted) this.#touch();
return this.status();
}
startRegistration() {
this.#assertOpen();
const id = this.#createRegistrationId();
if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id) || this.#registrations.has(id)) {
throw new Error('Registration id generator returned an invalid or duplicate id');
}
const record = { id, manager: null, botId: null, createdNew: false, cancelled: false };
record.manager = new RegistrationManager({
registerApp: this.#registerApp,
onCredentials: (result) => this.#serializeConfig(() => this.#acceptCredentials(record, result)),
});
this.#registrations.set(id, record);
this.#latestRegistrationId = id;
this.#trimRegistrations();
record.manager.start({
source: 'deepseek-harness',
createOnly: true,
appPreset: {
name: '{user} 的北汇星河 AI 助手',
desc: '连接飞书与 DeepSeek Harness,在聊天中使用企业 AI 助手。',
},
addons: {
preset: false,
scopes: { tenant: [...REQUIRED_TENANT_SCOPES] },
events: { items: { tenant: ['im.message.receive_v1'] } },
},
});
this.#touch();
return this.registrationStatus(id);
}
hasRegistration(attemptId) {
return this.#registrations.has(attemptId);
}
registrationStatus(attemptId) {
const record = this.#registrations.get(attemptId);
if (!record) return null;
return this.#status({ registration: record, selectedBotId: record.botId });
}
async cancelRegistration(attemptId = this.#latestRegistrationId) {
const record = this.#registrations.get(attemptId);
if (!record) return this.status();
if (!MUTABLE_REGISTRATION_STATES.has(record.manager.status().state)) {
return this.registrationStatus(attemptId);
}
record.cancelled = true;
record.manager.cancel();
await this.#serializeConfig(async () => {
if (record.createdNew && record.botId
&& this.#botOwnership.get(record.botId) === record.id
&& this.#configStore.getBot(record.botId)) {
await this.#withBotTransition(record.botId, () => this.#deleteBot(record.botId));
}
});
this.#touch();
return this.registrationStatus(attemptId) ?? this.status();
}
status(botId) {
return this.#status({
registration: this.#registrations.get(this.#latestRegistrationId) ?? null,
selectedBotId: botId,
});
}
async reconnectBot(botId) {
this.#assertOpen();
return this.#withBotTransition(botId, async () => {
const config = this.#requireBot(botId);
if (config.deletionPending) {
this.#botErrors.set(botId, {
code: 'deletion_pending',
message: '机器人正在等待完成本地删除,请重试移除。',
});
return this.status(botId);
}
if (isConnected(connectionStatus(this.#runtimes.get(botId)))) {
return this.status(botId);
}
let resolved;
try {
resolved = await this.#credentials.resolve(config.secretRef);
} catch {
resolved = null;
}
if (!resolved?.value) {
this.#botErrors.set(botId, {
code: 'missing_credentials',
message: '机器人凭据缺失,请删除后重新扫码接入。',
});
this.#touch();
return this.status(botId);
}
try {
await this.#startRuntime(config, resolved.value);
this.#botErrors.delete(botId);
} catch {
this.#botErrors.set(botId, {
code: 'connection_failed',
message: '机器人暂时无法连接飞书,请重试。',
});
}
this.#touch();
return this.status(botId);
});
}
async disconnectBot(botId) {
this.#assertOpen();
// An operational pause only: credentials/config remain durable, so the
// bot reconnects on the next Host start unless it is explicitly deleted.
return this.#withBotTransition(botId, async () => {
this.#requireBot(botId);
await this.#stopRuntime(botId);
this.#botErrors.delete(botId);
this.#touch();
return this.status(botId);
});
}
async deleteBot(botId) {
this.#assertOpen();
return this.#serializeConfig(() => this.#withBotTransition(botId, async () => {
this.#requireBot(botId);
await this.#deleteBot(botId);
this.#touch();
return this.status();
}));
}
// Compatibility methods for the original one-bot browser contract.
async reconnect() {
const bot = this.#configStore.list()[0];
return bot ? this.reconnectBot(bot.id) : this.status();
}
async disconnect() {
const bot = this.#configStore.list()[0];
return bot ? this.deleteBot(bot.id) : this.status();
}
async close() {
if (this.#closed) return;
this.#closed = true;
for (const record of this.#registrations.values()) {
if (MUTABLE_REGISTRATION_STATES.has(record.manager.status().state)) {
record.cancelled = true;
record.manager.cancel();
}
}
await this.#configTransition;
await Promise.allSettled([...this.#botTransitions.values()]);
await Promise.allSettled([...this.#runtimes.keys()].map((id) => this.#stopRuntime(id)));
}
#status({ registration, selectedBotId } = {}) {
const bots = this.#configStore.list().map((config) => {
const connection = connectionStatus(this.#runtimes.get(config.id));
const connected = isConnected(connection);
const error = this.#botErrors.get(config.id) ?? null;
return {
botId: config.id,
phase: botPhase({ connected, error, connection }),
connected,
configured: true,
bot: publicBot(config),
connection,
error,
};
});
const registrationSnapshot = registration ? this.#registrationSnapshot(registration) : {
state: 'idle', attempt: 0, updatedAt: Date.now(),
};
const registering = ACTIVE_REGISTRATION_STATES.has(registrationSnapshot.state);
const connecting = registrationSnapshot.state === 'saving';
const registrationOwnsProjection = Boolean(registration) && (registering || connecting);
const selected = bots.find((bot) => bot.botId === selectedBotId)
?? (registrationOwnsProjection ? null : (bots[0] ?? null));
const aggregateConnected = bots.some((bot) => bot.connected);
let phase = selected?.phase ?? 'unconfigured';
if (registering) phase = 'registering';
else if (connecting) phase = 'connecting';
else if (registrationSnapshot.state === 'error' && !selected) phase = 'error';
return {
schemaVersion: 2,
revision: this.#revision,
phase,
connected: selected?.connected ?? false,
configured: bots.length > 0,
bot: selected?.bot ?? null,
connection: selected?.connection ?? idleConnection(),
error: selected?.error ?? registrationSnapshot.error ?? null,
registration: registrationSnapshot,
bots,
totals: {
configured: bots.length,
connected: bots.filter((bot) => bot.connected).length,
},
anyConnected: aggregateConnected,
};
}
#registrationSnapshot(record) {
const snapshot = record.manager.status();
return {
...snapshot,
attempt: record.id,
...(record.botId ? { botId: record.botId } : {}),
};
}
async #acceptCredentials(record, result) {
if (record.cancelled) throw new Error('Registration was cancelled');
const appId = result.client_id;
const appSecret = result.client_secret;
const ownerOpenId = result.user_info?.open_id;
const domain = result.user_info?.tenant_brand === 'lark' ? 'lark' : 'feishu';
if (!ownerOpenId) throw new Error('Feishu registration returned no owner open_id');
const bot = await this.#verifyApp({ appId, appSecret, domain });
if (record.cancelled) throw new Error('Registration was cancelled');
const existing = this.#configStore.list().find((candidate) => candidate.appId === appId);
const botId = existing?.id ?? this.#createBotId();
if (typeof botId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(botId)
|| (!existing && this.#configStore.getBot(botId))) {
throw new Error('Bot id generator returned an invalid or duplicate id');
}
const secretRef = existing?.secretRef ?? secretRefFor(botId);
const previousOwnership = this.#botOwnership.get(botId);
const previousSecret = await this.#credentials.resolve(secretRef).catch(() => undefined);
await this.#credentials.set(secretRef, appSecret);
let config;
try {
config = await this.#configStore.saveBot({
...existing,
id: botId,
appId,
secretRef,
ownerOpenIds: [...new Set([...(existing?.ownerOpenIds ?? []), ownerOpenId])],
domain,
botName: bot.name,
botOpenId: bot.openId,
activated: bot.activated,
deletionPending: false,
connectedAt: new Date().toISOString(),
createdAt: existing?.createdAt ?? new Date().toISOString(),
});
record.botId = botId;
record.createdNew = !existing;
this.#botOwnership.set(botId, record.id);
} catch (error) {
try {
await this.#restoreCredential(secretRef, previousSecret);
} catch (restoreError) {
throw new Error('Unable to restore the Feishu credential after a config failure.', {
cause: restoreError,
});
}
throw error;
}
if (record.cancelled) {
if (record.createdNew) {
await this.#withBotTransition(botId, () => this.#deleteBot(botId));
} else {
await this.#configStore.saveBot(existing);
await this.#restoreCredential(secretRef, previousSecret);
if (previousOwnership) this.#botOwnership.set(botId, previousOwnership);
else this.#botOwnership.delete(botId);
}
throw new Error('Registration was cancelled');
}
let cancellationRolledBack = false;
try {
await this.#withBotTransition(botId, () => this.#startRuntime(config, appSecret));
if (record.cancelled) {
if (record.createdNew) {
await this.#withBotTransition(botId, () => this.#deleteBot(botId));
} else {
await this.#configStore.saveBot(existing);
await this.#restoreCredential(secretRef, previousSecret);
if (previousOwnership) this.#botOwnership.set(botId, previousOwnership);
else this.#botOwnership.delete(botId);
if (previousSecret?.value && !existing.deletionPending) {
await this.#withBotTransition(botId, () => this.#startRuntime(existing, previousSecret.value));
} else {
await this.#withBotTransition(botId, () => this.#stopRuntime(botId));
}
}
cancellationRolledBack = true;
throw new Error('Registration was cancelled');
}
this.#botErrors.delete(botId);
this.#touch();
} catch (error) {
if (record.cancelled) {
if (!cancellationRolledBack && record.createdNew && this.#configStore.getBot(botId)) {
await this.#withBotTransition(botId, () => this.#deleteBot(botId));
} else if (!cancellationRolledBack && existing) {
await this.#configStore.saveBot(existing);
await this.#restoreCredential(secretRef, previousSecret);
if (previousOwnership) this.#botOwnership.set(botId, previousOwnership);
else this.#botOwnership.delete(botId);
if (!this.#closed && previousSecret?.value && !existing.deletionPending) {
await this.#withBotTransition(botId, () => this.#startRuntime(existing, previousSecret.value));
} else {
await this.#withBotTransition(botId, () => this.#stopRuntime(botId));
}
}
this.#touch();
throw error;
}
if (existing && previousSecret?.value) {
try {
await this.#configStore.saveBot(existing);
await this.#restoreCredential(secretRef, previousSecret);
if (previousOwnership) this.#botOwnership.set(botId, previousOwnership);
else this.#botOwnership.delete(botId);
if (!existing.deletionPending) {
await this.#withBotTransition(botId, () => this.#startRuntime(existing, previousSecret.value));
this.#botErrors.delete(botId);
} else {
await this.#withBotTransition(botId, () => this.#stopRuntime(botId));
this.#botErrors.set(botId, {
code: 'deletion_pending',
message: '机器人正在等待完成本地删除,请重试移除。',
});
}
this.#touch();
throw error;
} catch (restoreError) {
if (restoreError === error) throw error;
this.#botErrors.set(botId, {
code: 'connection_failed',
message: '机器人连接更新失败,且原连接无法恢复,请重试。',
});
this.#touch();
throw new Error('Unable to restore the previous Feishu bot connection.', {
cause: restoreError,
});
}
}
this.#botErrors.set(botId, {
code: 'connection_failed',
message: '机器人已经创建,但长连接未就绪,请点击重试。',
});
this.#touch();
throw error;
}
}
async #startRuntime(config, appSecret) {
await this.#stopRuntime(config.id);
const runtime = await this.#createRuntime({
botId: config.id,
config,
appSecret,
});
this.#runtimes.set(config.id, runtime);
try {
await runtime.start();
} catch (error) {
if (this.#runtimes.get(config.id) === runtime) this.#runtimes.delete(config.id);
await runtime.stop({ preserveError: true }).catch(() => undefined);
throw error;
}
}
async #stopRuntime(botId) {
const runtime = this.#runtimes.get(botId);
this.#runtimes.delete(botId);
if (runtime) await runtime.stop();
}
async #deleteBot(botId) {
let config = this.#configStore.getBot(botId);
if (!config) return;
if (!config.deletionPending) {
config = await this.#configStore.saveBot({ ...config, deletionPending: true });
}
await this.#stopRuntime(botId);
try {
await this.#credentials.unset(config.secretRef);
} catch (error) {
this.#botErrors.set(botId, {
code: 'credential_removal_failed',
message: '无法删除机器人凭据,请稍后重试。',
});
throw new Error('Unable to remove the Feishu credential.', { cause: error });
}
try {
await this.#deleteState({ botId, config });
} catch (error) {
this.#botErrors.set(botId, {
code: 'state_cleanup_failed',
message: '无法删除机器人的本地会话数据,请稍后重试。',
});
throw new Error('Unable to remove the Feishu bot session state.', { cause: error });
}
await this.#configStore.removeBot(botId);
this.#botErrors.delete(botId);
this.#botOwnership.delete(botId);
}
async #restoreCredential(secretRef, previous) {
if (previous?.value) await this.#credentials.set(secretRef, previous.value);
else await this.#credentials.unset(secretRef);
}
#requireBot(botId) {
const config = this.#configStore.getBot(botId);
if (!config) throw new Error('Unknown Feishu bot');
return config;
}
#assertOpen() {
if (this.#closed) throw new Error('The Feishu controller is closed');
}
#serializeConfig(operation) {
const result = this.#configTransition.then(operation, operation);
this.#configTransition = result.then(() => undefined, () => undefined);
return result;
}
#withBotTransition(botId, operation) {
const previous = this.#botTransitions.get(botId) ?? Promise.resolve();
const result = previous.then(operation, operation);
const tail = result.then(() => undefined, () => undefined);
this.#botTransitions.set(botId, tail);
void tail.finally(() => {
if (this.#botTransitions.get(botId) === tail) this.#botTransitions.delete(botId);
});
return result;
}
#trimRegistrations() {
if (this.#registrations.size <= 32) return;
for (const [id, record] of this.#registrations) {
if (id === this.#latestRegistrationId) continue;
const state = record.manager.status().state;
if (!ACTIVE_REGISTRATION_STATES.has(state) && state !== 'saving') {
this.#registrations.delete(id);
}
if (this.#registrations.size <= 32) break;
}
}
#touch() {
this.#revision += 1;
}
}

View file

@ -0,0 +1,204 @@
import { createHash } from 'node:crypto';
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
export const LEGACY_FEISHU_SECRET_REF = 'DSH_FEISHU_APP_SECRET';
function cleanString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function safeId(value) {
const id = cleanString(value);
return id && /^[A-Za-z0-9_-]{1,128}$/.test(id) ? id : null;
}
function legacyBotId(appId) {
return `bot_${createHash('sha256').update(appId).digest('hex').slice(0, 24)}`;
}
function normalizeOwners(value) {
const candidates = Array.isArray(value.ownerOpenIds)
? value.ownerOpenIds
: [value.ownerOpenId];
return [...new Set(candidates.map(cleanString).filter(Boolean))];
}
function normalizeBot(value, { legacy = false } = {}) {
if (!value || typeof value !== 'object') return null;
const appId = cleanString(value.appId);
const ownerOpenIds = normalizeOwners(value);
if (!appId || ownerOpenIds.length === 0) return null;
const id = safeId(value.id) ?? (legacy ? legacyBotId(appId) : null);
const secretRef = cleanString(value.secretRef) ?? (legacy ? LEGACY_FEISHU_SECRET_REF : null);
if (!id || !secretRef) return null;
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(secretRef)) return null;
const domain = value.domain === 'lark' ? 'lark' : 'feishu';
return Object.freeze({
id,
appId,
secretRef,
ownerOpenIds: Object.freeze(ownerOpenIds),
domain,
botName: cleanString(value.botName),
botOpenId: cleanString(value.botOpenId),
activated: value.activated ?? null,
deletionPending: value.deletionPending === true,
connectedAt: cleanString(value.connectedAt),
createdAt: cleanString(value.createdAt) ?? cleanString(value.connectedAt),
});
}
function normalizeDocument(value) {
if (!value || typeof value !== 'object') return null;
if (value.version === 2 && Array.isArray(value.bots)) {
const bots = value.bots.map((bot) => normalizeBot(bot));
if (bots.some((bot) => bot === null)) {
throw new Error('dsh-feishu config contains an invalid bot entry');
}
const ids = new Set();
const refs = new Set();
const appIds = new Set();
for (const bot of bots) {
if (ids.has(bot.id) || refs.has(bot.secretRef) || appIds.has(bot.appId)) {
throw new Error('dsh-feishu config contains duplicate bot identities');
}
ids.add(bot.id);
refs.add(bot.secretRef);
appIds.add(bot.appId);
}
return { value: Object.freeze({ version: 2, bots: Object.freeze(bots) }), migrated: false };
}
// Version 1 was a single non-secret bot object. Preserve its existing
// credential reference so an environment-backed secret remains usable.
const legacyBot = normalizeBot(value, { legacy: true });
if (!legacyBot) return null;
return {
value: Object.freeze({ version: 2, bots: Object.freeze([legacyBot]) }),
migrated: true,
};
}
/** Stores only non-secret onboarding facts for all Feishu bots. */
export class PluginConfigStore {
#path;
#value = Object.freeze({ version: 2, bots: Object.freeze([]) });
#writeQueue = Promise.resolve();
constructor(path) {
this.#path = path;
}
async load() {
try {
const parsed = JSON.parse(await readFile(this.#path, 'utf8'));
const normalized = normalizeDocument(parsed);
if (!normalized) throw new Error('dsh-feishu config is incomplete or invalid');
this.#value = normalized.value;
if (normalized.migrated) await this.#writeDocument(this.#value);
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
this.#value = Object.freeze({ version: 2, bots: Object.freeze([]) });
}
return this;
}
/** Backward-compatible single-bot view used by the original controller. */
get() {
const bot = this.#value.bots[0];
if (!bot) return null;
const result = structuredClone(bot);
result.ownerOpenId = result.ownerOpenIds[0];
return result;
}
list() {
return structuredClone(this.#value.bots);
}
getBot(id) {
const bot = this.#value.bots.find((candidate) => candidate.id === id);
return bot ? structuredClone(bot) : null;
}
/** Backward-compatible save replaces the original single-bot view. */
async save(value) {
const fallback = { ...value };
if (!fallback.id) fallback.id = legacyBotId(cleanString(fallback.appId) ?? 'invalid');
if (!fallback.secretRef) fallback.secretRef = LEGACY_FEISHU_SECRET_REF;
const normalized = normalizeBot(fallback);
if (!normalized) throw new Error('Refusing to persist incomplete dsh-feishu configuration');
await this.#replaceBots([normalized]);
return this.get();
}
async saveBot(value) {
const normalized = normalizeBot(value);
if (!normalized) throw new Error('Refusing to persist incomplete dsh-feishu bot configuration');
return this.#mutate((bots) => {
const collision = bots.find((bot) => bot.secretRef === normalized.secretRef && bot.id !== normalized.id);
if (collision) throw new Error('Refusing to share a credential reference between Feishu bots');
const appCollision = bots.find((bot) => bot.appId === normalized.appId && bot.id !== normalized.id);
if (appCollision) throw new Error('Refusing to persist the same Feishu app twice');
const index = bots.findIndex((bot) => bot.id === normalized.id);
if (index === -1) bots.push(normalized);
else bots[index] = normalized;
return structuredClone(normalized);
});
}
async removeBot(id) {
if (!safeId(id)) throw new TypeError('Invalid Feishu bot id');
return this.#mutate((bots) => {
const index = bots.findIndex((bot) => bot.id === id);
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 = Object.freeze({ version: 2, bots: Object.freeze([]) });
});
this.#writeQueue = operation.then(() => undefined, () => undefined);
await operation;
}
async #replaceBots(bots) {
const document = Object.freeze({ version: 2, bots: Object.freeze([...bots]) });
const operation = this.#writeQueue.then(async () => {
await this.#writeDocument(document);
this.#value = 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: 2, bots: Object.freeze(bots) });
await this.#writeDocument(document);
this.#value = document;
});
this.#writeQueue = operation.then(() => undefined, () => undefined);
await operation;
return result;
}
async #writeDocument(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,248 @@
import { RegistrationManager } from './registration-manager.mjs';
export const FEISHU_SECRET_REF = 'DSH_FEISHU_APP_SECRET';
export const REQUIRED_TENANT_SCOPES = Object.freeze([
'im:message.p2p_msg:readonly',
'im:message.group_at_msg:readonly',
'im:message:send_as_bot',
'im:message.reactions:write_only',
'im:message:recall',
'cardkit:card:write',
]);
function safeConnectionStatus(runtime) {
if (!runtime) return {
ready: false,
feishuLongConnectionState: 'idle',
harnessReachable: false,
};
return runtime.status;
}
function publicBot(config) {
if (!config) return null;
const appIdMasked = config.appId.length > 12
? `${config.appId.slice(0, 8)}••••${config.appId.slice(-4)}`
: 'cli_••••';
return {
name: config.botName,
appIdMasked,
openId: config.botOpenId,
activated: config.activated,
domain: config.domain,
};
}
/** Coordinates QR provisioning, durable credentials and the live chat runtime. */
export class DshFeishuController {
#registerApp;
#verifyApp;
#credentials;
#configStore;
#createRuntime;
#registration;
#runtime = null;
#lastError = null;
#transition = Promise.resolve();
constructor({ registerApp, verifyApp, credentials, configStore, createRuntime }) {
if (typeof registerApp !== 'function') throw new Error('registerApp is required');
if (typeof verifyApp !== 'function') throw new Error('verifyApp is required');
if (!credentials) throw new Error('credentials service is required');
if (!configStore) throw new Error('config store is required');
if (typeof createRuntime !== 'function') throw new Error('createRuntime is required');
this.#registerApp = registerApp;
this.#verifyApp = verifyApp;
this.#credentials = credentials;
this.#configStore = configStore;
this.#createRuntime = createRuntime;
this.#registration = new RegistrationManager({
registerApp: this.#registerApp,
onCredentials: (result) => this.#serialize(() => this.#acceptCredentials(result)),
});
}
async initialize() {
const config = this.#configStore.get();
if (!config) return this.status();
return this.#serialize(async () => {
const resolved = await this.#credentials.resolve(FEISHU_SECRET_REF);
if (!resolved?.value) {
this.#lastError = {
code: 'missing_credentials',
message: '机器人凭据缺失,请重新扫码接入。',
};
return this.status();
}
try {
await this.#startRuntime(config, resolved.value);
this.#lastError = null;
} catch {
this.#lastError = {
code: 'connection_failed',
message: '机器人暂时无法连接飞书,请重试。',
};
}
return this.status();
});
}
startRegistration() {
this.#lastError = null;
this.#registration.start({
source: 'deepseek-harness',
createOnly: true,
appPreset: {
name: '{user} 的北汇星河 AI 助手',
desc: '连接飞书与 DeepSeek Harness,在聊天中使用企业 AI 助手。',
},
addons: {
preset: false,
scopes: { tenant: [...REQUIRED_TENANT_SCOPES] },
events: { items: { tenant: ['im.message.receive_v1'] } },
},
});
return this.status();
}
cancelRegistration() {
this.#registration.cancel();
return this.status();
}
async reconnect() {
return this.#serialize(async () => {
const config = this.#configStore.get();
const resolved = await this.#credentials.resolve(FEISHU_SECRET_REF);
if (!config || !resolved?.value) {
this.#lastError = {
code: 'missing_credentials',
message: '没有可用的机器人凭据,请重新扫码接入。',
};
return this.status();
}
try {
await this.#startRuntime(config, resolved.value);
this.#lastError = null;
} catch {
this.#lastError = {
code: 'connection_failed',
message: '机器人暂时无法连接飞书,请重试。',
};
}
return this.status();
});
}
async disconnect() {
this.#registration.cancel();
return this.#serialize(async () => {
await this.#stopRuntime();
await this.#configStore.clear();
try {
await this.#credentials.unset(FEISHU_SECRET_REF);
} catch {
// A read-only environment value may shadow the managed store. Clearing
// the non-secret config still prevents automatic reuse of that value.
}
this.#lastError = null;
return this.status();
});
}
async close() {
this.#registration.cancel();
await this.#serialize(() => this.#stopRuntime());
}
status() {
const config = this.#configStore.get();
const registration = this.#registration.status();
const connection = safeConnectionStatus(this.#runtime);
const connected = connection.ready === true
&& connection.feishuLongConnectionState === 'connected'
&& connection.harnessReachable === true;
let phase = 'unconfigured';
if (connected) phase = 'connected';
else if (['starting', 'qr_ready', 'polling', 'slow_down', 'domain_switched'].includes(registration.state)) {
phase = 'registering';
} else if (registration.state === 'saving') phase = 'connecting';
else if (this.#lastError || registration.state === 'error') phase = 'error';
else if (config) phase = 'disconnected';
return {
phase,
connected,
configured: Boolean(config),
bot: publicBot(config),
registration,
connection,
error: this.#lastError ?? registration.error ?? null,
};
}
async #acceptCredentials(result) {
const appId = result.client_id;
const appSecret = result.client_secret;
const ownerOpenId = result.user_info?.open_id;
const domain = result.user_info?.tenant_brand === 'lark' ? 'lark' : 'feishu';
if (!ownerOpenId) throw new Error('Feishu registration returned no owner open_id');
const bot = await this.#verifyApp({ appId, appSecret, domain });
await this.#credentials.set(FEISHU_SECRET_REF, appSecret);
let config;
try {
config = await this.#configStore.save({
appId,
ownerOpenId,
domain,
botName: bot.name,
botOpenId: bot.openId,
activated: bot.activated,
connectedAt: new Date().toISOString(),
});
} catch (error) {
await this.#credentials.unset(FEISHU_SECRET_REF).catch(() => undefined);
throw error;
}
try {
await this.#startRuntime(config, appSecret);
this.#lastError = null;
} catch (error) {
this.#lastError = {
code: 'connection_failed',
message: '机器人已经创建,但长连接未就绪,请点击重试。',
};
throw error;
}
}
async #startRuntime(config, appSecret) {
await this.#stopRuntime();
const runtime = await this.#createRuntime({ config, appSecret });
this.#runtime = runtime;
try {
await runtime.start();
} catch (error) {
if (this.#runtime === runtime) this.#runtime = null;
await runtime.stop({ preserveError: true }).catch(() => undefined);
throw error;
}
}
async #stopRuntime() {
const runtime = this.#runtime;
this.#runtime = null;
if (runtime) await runtime.stop();
}
#serialize(operation) {
const result = this.#transition.then(operation, operation);
this.#transition = result.then(() => undefined, () => undefined);
return result;
}
}

View file

@ -0,0 +1,345 @@
const ACTIVE_STATES = new Set([
'starting',
'qr_ready',
'polling',
'slow_down',
'domain_switched',
'saving',
]);
const SDK_POLLING_STATES = new Set([
'polling',
'slow_down',
'domain_switched',
]);
export const REGISTRATION_STATES = Object.freeze({
IDLE: 'idle',
STARTING: 'starting',
QR_READY: 'qr_ready',
POLLING: 'polling',
SLOW_DOWN: 'slow_down',
DOMAIN_SWITCHED: 'domain_switched',
SAVING: 'saving',
SUCCEEDED: 'succeeded',
EXPIRED: 'expired',
CANCELLED: 'cancelled',
ERROR: 'error',
});
function errorCode(error) {
if (['access_denied', 'expired_token', 'abort'].includes(error?.code)) return error.code;
return 'registration_failed';
}
function publicError(error) {
const code = errorCode(error);
const messages = {
access_denied: 'Registration was denied.',
abort: 'Registration was cancelled.',
expired_token: 'The registration QR code expired.',
};
// SDK/network errors are deliberately not copied verbatim. Besides keeping
// the API stable, this prevents a downstream error from reflecting a secret
// into a status response.
return {
code,
message: messages[code] ?? 'Unable to register the Feishu app.',
};
}
function expirySeconds(value) {
const seconds = Number(value);
if (!Number.isFinite(seconds) || seconds <= 0) {
throw new TypeError('registerApp onQRCodeReady returned an invalid expireIn');
}
return seconds;
}
function copyUserInfo(userInfo) {
if (userInfo === undefined) return undefined;
if (userInfo === null || typeof userInfo !== 'object' || Array.isArray(userInfo)) {
throw new TypeError('registerApp returned invalid user_info');
}
return { ...userInfo };
}
/**
* Owns one Feishu device-registration attempt at a time.
*
* `start()` intentionally does not await the long-running SDK poll. Consumers
* start an attempt and then poll `status()` until it reaches a terminal state.
* The App Secret never becomes manager state and is only handed to the injected
* `onCredentials` callback.
*/
export class RegistrationManager {
#registerApp;
#onCredentials;
#now;
#setTimeout;
#clearTimeout;
#attempt = 0;
#active = null;
#snapshot;
constructor({
registerApp,
onCredentials,
now = Date.now,
setTimeout: setTimeoutFn = globalThis.setTimeout,
clearTimeout: clearTimeoutFn = globalThis.clearTimeout,
} = {}) {
if (typeof registerApp !== 'function') {
throw new TypeError('RegistrationManager requires a registerApp function');
}
if (typeof onCredentials !== 'function') {
throw new TypeError('RegistrationManager requires an onCredentials function');
}
if (typeof now !== 'function' || typeof setTimeoutFn !== 'function' || typeof clearTimeoutFn !== 'function') {
throw new TypeError('RegistrationManager clock dependencies must be functions');
}
this.#registerApp = registerApp;
this.#onCredentials = onCredentials;
this.#now = now;
this.#setTimeout = setTimeoutFn;
this.#clearTimeout = clearTimeoutFn;
this.#snapshot = this.#makeSnapshot(null, REGISTRATION_STATES.IDLE);
}
start(registerOptions = {}) {
if (registerOptions === null || typeof registerOptions !== 'object' || Array.isArray(registerOptions)) {
throw new TypeError('Registration options must be an object');
}
this.#supersedeActiveAttempt();
const run = {
id: ++this.#attempt,
controller: new AbortController(),
qrCodeUrl: null,
expiresAt: null,
pollIntervalSeconds: null,
expiryTimer: null,
};
this.#active = run;
this.#snapshot = this.#makeSnapshot(run, REGISTRATION_STATES.STARTING);
const options = {
...registerOptions,
signal: run.controller.signal,
onQRCodeReady: (info) => this.#onQRCodeReady(run, info),
onStatusChange: (info) => this.#onStatusChange(run, info),
};
// Put the SDK invocation on a microtask so a synchronous throw and a
// Promise rejection follow the same path without making start() blocking.
const registration = Promise.resolve().then(() => this.#registerApp(options));
void registration.then(
(result) => this.#onRegistrationSucceeded(run, result),
(error) => this.#onRegistrationFailed(run, error),
);
return this.status();
}
status() {
this.#expireIfNeeded();
const snapshot = { ...this.#snapshot };
if (snapshot.error) snapshot.error = { ...snapshot.error };
const run = this.#active;
if (run && run.expiresAt !== null && ACTIVE_STATES.has(snapshot.state)) {
snapshot.remainingSeconds = Math.max(0, Math.ceil((run.expiresAt - this.#now()) / 1000));
}
return snapshot;
}
cancel() {
const run = this.#active;
if (!run) return this.status();
this.#finishRun(run, REGISTRATION_STATES.CANCELLED, {
error: {
code: 'abort',
message: 'Registration was cancelled.',
},
});
run.controller.abort();
return this.status();
}
#isCurrent(run) {
return this.#active === run;
}
#makeSnapshot(run, state, extra = {}) {
const snapshot = {
state,
attempt: run?.id ?? this.#attempt,
updatedAt: this.#now(),
...extra,
};
if (run?.qrCodeUrl && ACTIVE_STATES.has(state)) {
snapshot.qrCodeUrl = run.qrCodeUrl;
snapshot.expiresAt = run.expiresAt;
}
if (run?.pollIntervalSeconds !== null && ACTIVE_STATES.has(state)) {
snapshot.pollIntervalSeconds = run.pollIntervalSeconds;
}
return snapshot;
}
#setRunState(run, state, extra = {}) {
if (!this.#isCurrent(run)) return;
this.#snapshot = this.#makeSnapshot(run, state, extra);
}
#onQRCodeReady(run, info) {
if (!this.#isCurrent(run)) return;
if (typeof info?.url !== 'string' || !info.url) {
throw new TypeError('registerApp onQRCodeReady returned an invalid URL');
}
const seconds = expirySeconds(info.expireIn);
run.qrCodeUrl = info.url;
run.expiresAt = this.#now() + (seconds * 1000);
this.#clearExpiryTimer(run);
run.expiryTimer = this.#setTimeout(() => this.#expireRun(run), seconds * 1000);
run.expiryTimer?.unref?.();
this.#setRunState(run, REGISTRATION_STATES.QR_READY);
}
#onStatusChange(run, info) {
if (!this.#isCurrent(run) || !SDK_POLLING_STATES.has(info?.status)) return;
if (info.status === REGISTRATION_STATES.SLOW_DOWN && Number.isFinite(Number(info.interval))) {
run.pollIntervalSeconds = Number(info.interval);
}
this.#setRunState(run, info.status);
}
async #onRegistrationSucceeded(run, result) {
if (!this.#isCurrent(run)) return;
const clientId = result?.client_id;
const clientSecret = result?.client_secret;
if (typeof clientId !== 'string' || !clientId || typeof clientSecret !== 'string' || !clientSecret) {
this.#finishRun(run, REGISTRATION_STATES.ERROR, {
error: {
code: 'invalid_credentials',
message: 'Feishu registration returned invalid credentials.',
},
});
return;
}
let userInfo;
try {
userInfo = copyUserInfo(result.user_info);
} catch {
this.#finishRun(run, REGISTRATION_STATES.ERROR, {
error: {
code: 'invalid_credentials',
message: 'Feishu registration returned invalid credentials.',
},
});
return;
}
// Once the SDK has returned credentials, QR expiry no longer applies.
// Remove the device URL before awaiting persistence so it also disappears
// from the public `saving` status.
this.#clearExpiryTimer(run);
run.qrCodeUrl = null;
run.expiresAt = null;
run.pollIntervalSeconds = null;
this.#setRunState(run, REGISTRATION_STATES.SAVING);
try {
await this.#onCredentials({
client_id: clientId,
client_secret: clientSecret,
user_info: userInfo,
});
} catch {
if (this.#isCurrent(run)) {
this.#finishRun(run, REGISTRATION_STATES.ERROR, {
error: {
code: 'credentials_callback_failed',
message: 'Unable to store the Feishu credentials.',
},
});
}
return;
}
if (this.#isCurrent(run)) {
this.#finishRun(run, REGISTRATION_STATES.SUCCEEDED);
}
}
#onRegistrationFailed(run, error) {
if (!this.#isCurrent(run)) return;
const code = errorCode(error);
if (code === 'expired_token') {
this.#finishRun(run, REGISTRATION_STATES.EXPIRED, {
error: publicError(error),
});
return;
}
if (code === 'abort') {
this.#finishRun(run, REGISTRATION_STATES.CANCELLED, {
error: publicError(error),
});
return;
}
this.#finishRun(run, REGISTRATION_STATES.ERROR, {
error: publicError(error),
});
}
#expireIfNeeded() {
const run = this.#active;
if (run && run.expiresAt !== null && this.#now() >= run.expiresAt) {
this.#expireRun(run);
}
}
#expireRun(run) {
if (!this.#isCurrent(run)) return;
this.#finishRun(run, REGISTRATION_STATES.EXPIRED, {
error: {
code: 'expired_token',
message: 'The registration QR code expired.',
},
});
run.controller.abort();
}
#finishRun(run, state, extra = {}) {
if (!this.#isCurrent(run)) return;
this.#clearExpiryTimer(run);
this.#snapshot = this.#makeSnapshot(run, state, extra);
this.#active = null;
}
#clearExpiryTimer(run) {
if (run.expiryTimer !== null) {
this.#clearTimeout(run.expiryTimer);
run.expiryTimer = null;
}
}
#supersedeActiveAttempt() {
const previous = this.#active;
if (!previous) return;
this.#clearExpiryTimer(previous);
this.#active = null;
previous.controller.abort();
}
}
export default RegistrationManager;

View file

@ -0,0 +1,71 @@
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
const EMPTY_STATE = Object.freeze({ version: 1, sessions: {}, seenMessageIds: [] });
export class StateStore {
#path;
#state = structuredClone(EMPTY_STATE);
#writeQueue = Promise.resolve();
constructor(path) {
this.#path = path;
}
async load() {
try {
const parsed = JSON.parse(await readFile(this.#path, 'utf8'));
this.#state = {
version: 1,
sessions: parsed.sessions && typeof parsed.sessions === 'object' ? parsed.sessions : {},
seenMessageIds: Array.isArray(parsed.seenMessageIds) ? parsed.seenMessageIds.slice(-1000) : [],
};
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
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 > 1000) {
this.#state.seenMessageIds.splice(0, this.#state.seenMessageIds.length - 1000);
}
await this.#persist();
}
snapshot() {
return structuredClone(this.#state);
}
async #persist() {
const snapshot = JSON.stringify(this.#state, null, 2) + '\n';
this.#writeQueue = 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);
});
await this.#writeQueue;
}
}

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;
}
}