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,202 @@
export const DINGTALK_RPC_CHANNEL = '/dingtalk';
export const DINGTALK_ENDPOINTS = Object.freeze({
status: 'connection.status',
beginProvisioning: 'provision.begin',
pollProvisioning: 'provision.poll',
cancelProvisioning: 'provision.cancel',
reconnectBot: 'bot.reconnect',
deleteBot: 'bot.delete',
});
const ACCOUNT_STATES = new Set(['connected', 'connecting', 'offline', 'error']);
const SNAPSHOT_STATES = new Set(['disconnected', 'offline', 'provisioning', 'connected', 'degraded']);
const PROVISION_STATES = new Set([
'starting',
'pending',
'scanned',
'authorizing',
'creating',
'connecting',
'connected',
'expired',
'failed',
'cancelled',
]);
const HEALTH_STATES = new Set(['healthy', 'checking', 'degraded', 'offline']);
const FORBIDDEN_ERROR_FIELDS = /(client[_-]?secret|secret[_-]?ref|device[_-]?code|app[_-]?secret|access[_-]?token|token)/i;
const QR_DATA_URL = /^data:image\/(?:png|webp);base64,[a-z\d+/]+={0,2}$/i;
const MAX_QR_SOURCE_LENGTH = 2 * 1024 * 1024;
function isRecord(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function optionalString(value, maxLength = 240) {
if (typeof value !== 'string') return undefined;
const trimmed = value.trim();
return trimmed ? trimmed.slice(0, maxLength) : undefined;
}
function opaqueId(value) {
const id = optionalString(value, 128);
return id && /^[a-z\d_-]+$/i.test(id) ? id : undefined;
}
function timestamp(value) {
if (typeof value === 'number' && Number.isFinite(value)) return value;
if (typeof value === 'string' && value.trim()) {
const parsed = Date.parse(value);
return Number.isNaN(parsed) ? undefined : parsed;
}
return undefined;
}
function nonNegativeInteger(value) {
const number = Number(value);
return Number.isSafeInteger(number) && number >= 0 ? number : 0;
}
function clamp(value, min, max, fallback) {
const number = Number(value);
return Number.isFinite(number) ? Math.min(max, Math.max(min, number)) : fallback;
}
function safeErrorCode(value, fallback) {
const code = optionalString(value, 80);
return code && /^[a-z][a-z\d_.:-]*$/i.test(code) && !FORBIDDEN_ERROR_FIELDS.test(code)
? code
: fallback;
}
function sanitizeMessage(value, fallback) {
const message = optionalString(value, 480) ?? fallback;
if (FORBIDDEN_ERROR_FIELDS.test(message)) return fallback;
return message.replace(/([=:]\s*)[^\s,;,。]+/g, '$1••••••').slice(0, 240);
}
function normalizeError(value, fallbackCode, fallbackMessage) {
if (!isRecord(value)) return undefined;
return {
code: safeErrorCode(value.code, fallbackCode),
message: sanitizeMessage(value.message, fallbackMessage),
};
}
export function unwrapRpcResult(result) {
if (!isRecord(result) || typeof result.ok !== 'boolean') {
throw new Error('钉钉服务返回了无法识别的响应');
}
if (!result.ok) {
const error = new Error(sanitizeMessage(result.error?.message, '钉钉操作失败'));
error.code = safeErrorCode(result.error?.code, 'DINGTALK_RPC_ERROR');
throw error;
}
return result.value;
}
export function safeQrSource(value) {
if (typeof value !== 'string' || value.length > MAX_QR_SOURCE_LENGTH) return undefined;
return QR_DATA_URL.test(value) ? value : undefined;
}
export function normalizeProvisioning(value, now = Date.now()) {
const source = isRecord(value?.provisioning) ? value.provisioning : value;
if (!isRecord(source)) throw new Error('钉钉服务没有返回扫码绑定进度');
const attemptId = opaqueId(source.attemptId);
if (!attemptId) throw new Error('钉钉扫码服务没有返回有效的绑定任务');
const reportedStatus = optionalString(source.status, 32) ?? optionalString(source.state, 32);
const status = PROVISION_STATES.has(reportedStatus) ? reportedStatus : 'failed';
const expiresAt = timestamp(source.expiresAt)
?? now + clamp(source.expiresIn, 1, 2 * 60 * 60, 10 * 60) * 1_000;
const result = {
attemptId,
status,
expiresAt,
pollIntervalMs: clamp(source.pollIntervalMs, 1_000, 10_000, 3_000),
};
const qrCodeDataUrl = safeQrSource(source.qrCodeDataUrl);
if (qrCodeDataUrl) result.qrCodeDataUrl = qrCodeDataUrl;
if (opaqueId(source.botId)) result.botId = opaqueId(source.botId);
if (source.alreadyConnected === true) result.alreadyConnected = true;
const error = normalizeError(
source.error,
'DINGTALK_PROVISION_FAILED',
'钉钉机器人没有接入完成',
);
if (error) result.error = error;
return result;
}
function normalizeBot(value) {
if (!isRecord(value)) return undefined;
const botId = opaqueId(value.botId);
if (!botId) return undefined;
const bot = isRecord(value.bot) ? value.bot : {};
const connected = value.connected === true;
const reportedState = ACCOUNT_STATES.has(value.state) ? value.state : 'offline';
const state = connected ? 'connected' : reportedState === 'connected' ? 'connecting' : reportedState;
const health = isRecord(value.health) ? value.health : {};
const stats = isRecord(value.stats) ? value.stats : {};
return {
botId,
state,
connected,
configured: value.configured !== false,
bot: {
name: optionalString(bot.name, 100) ?? '钉钉机器人',
clientIdMasked: optionalString(bot.clientIdMasked, 140) ?? '已安全保存',
},
health: {
status: HEALTH_STATES.has(health.status)
? health.status
: connected ? 'healthy' : 'offline',
summary: optionalString(health.summary, 200)
?? (connected ? '钉钉 Stream 长连接运行正常' : '钉钉连接尚未就绪'),
lastCheckedAt: timestamp(health.lastCheckedAt),
lastConnectedAt: timestamp(health.lastConnectedAt),
},
stats: {
messagesReceived: nonNegativeInteger(stats.messagesReceived),
messagesReplied: nonNegativeInteger(stats.messagesReplied),
},
error: normalizeError(value.error, 'DINGTALK_ACCOUNT_ERROR', '钉钉连接尚未就绪') ?? null,
};
}
export function normalizeSnapshot(value) {
const source = isRecord(value?.snapshot) ? value.snapshot : value;
if (!isRecord(source) || !Array.isArray(source.bots)) {
throw new Error('钉钉服务没有返回有效的机器人列表');
}
const seen = new Set();
const bots = source.bots.map(normalizeBot).filter((bot) => {
if (!bot || seen.has(bot.botId)) return false;
seen.add(bot.botId);
return true;
});
return {
schemaVersion: Number.isSafeInteger(source.schemaVersion) ? source.schemaVersion : 1,
revision: nonNegativeInteger(source.revision),
state: SNAPSHOT_STATES.has(source.state) ? source.state : 'offline',
bots,
totals: {
configured: bots.length,
connected: bots.filter((bot) => bot.connected).length,
},
provisioning: source.provisioning ? normalizeProvisioning(source.provisioning) : null,
};
}
export function presentError(error) {
return {
code: safeErrorCode(error?.code, 'DINGTALK_ERROR'),
message: sanitizeMessage(error?.message, '钉钉操作失败,请稍后重试'),
};
}
export function formatRemaining(milliseconds) {
const seconds = Math.max(0, Math.ceil(Number(milliseconds) / 1_000) || 0);
return `${String(Math.floor(seconds / 60)).padStart(2, '0')}:${String(seconds % 60).padStart(2, '0')}`;
}

View file

@ -0,0 +1,661 @@
import * as React from 'react';
import {
DINGTALK_ENDPOINTS,
DINGTALK_RPC_CHANNEL,
formatRemaining,
normalizeProvisioning,
normalizeSnapshot,
presentError,
safeQrSource,
unwrapRpcResult,
} from './api.js';
import { installDingtalkStyles } from './styles.js';
const h = React.createElement;
const ACTIVE_PROVISION_STATES = new Set(['pending', 'scanned', 'authorizing', 'creating', 'connecting']);
export const name = 'dingtalk-settings';
export const inject = ['slots', 'connection'];
function DingtalkIcon({ size = 28 }) {
return h('svg', {
width: size,
height: size,
viewBox: '0 0 48 48',
fill: 'none',
xmlns: 'http://www.w3.org/2000/svg',
'aria-hidden': 'true',
focusable: 'false',
}, h('path', {
fill: 'currentColor',
d: 'M37.05 22.783c-6.758-5.216-14.378-12.128-22.73-19.538-.655-.585-1.242-.354-1.536.42-1.88 4.973-.058 9.386 2.889 11.932s7.368 4.912 10.058 6.155c.105.049.013.203-.093.163-4.953-2.182-8.397-3.765-13.07-7.368-.497-.388-1.01-.242-1.07.521-.384 4.748 2.657 8.483 6.058 9.745 2.1.781 4.398 1.212 6.53 1.474.109.015.084.178-.027.178-2.747.01-6.058-.654-8.935-1.751-.606-.233-.818.25-.722.633.491 2.008 2.974 5.076 6.926 5.73a12 12 0 0 0 2.228.115c.164 0 .208.089.154.217q-2.685 4.6-2.803 4.797c-.091.152-.036.275.156.275h3.543c.164 0 .264.106.18.246l-4.958 8.196c-.191.328.035.565.395.301s15.212-11.133 15.636-11.448c.195-.142.148-.327-.124-.327h-3.18c-.206 0-.252-.14-.111-.28.14-.141 3.602-3.594 4.837-4.888 1.283-1.35 1.938-3.825-.231-5.498',
}));
}
const Button = React.forwardRef(function Button(
{ children, kind = 'secondary', className = '', ...props },
ref,
) {
return h('button', {
...props,
ref,
type: 'button',
className: `ddt-button ${className}`.trim(),
'data-kind': kind,
}, children);
});
function Heading({ totals, adding, busy, onAdd, addButtonRef }) {
return h('div', { className: 'ddt-heading' },
h('div', { className: 'ddt-headingCopy' },
h('div', { className: 'ddt-eyebrow' }, 'Channel'),
h('h2', null, '钉钉机器人'),
h('p', null, '通过扫码把钉钉机器人接入 DeepSeek Harness')),
h('div', { className: 'ddt-tools' },
totals.configured > 0
? h('div', { className: 'ddt-badge' },
h('span', {
className: 'ddt-dot',
'data-tone': totals.connected > 0 ? 'success' : 'warning',
}),
h('span', null, `${totals.connected} / ${totals.configured} 在线`))
: null,
h('div', {
className: 'ddt-badge',
title: '应用密钥只写入 Harness Host 凭据服务,不会发送到浏览器',
}, '凭据仅保存在本机'),
h(Button, {
kind: 'primary',
onClick: onAdd,
disabled: adding || busy,
ref: addButtonRef,
}, adding ? '正在接入' : '扫码接入钉钉')));
}
function LoadingView() {
return h('div', { className: 'ddt-card ddt-loading', 'aria-busy': 'true' },
h('div', { className: 'ddt-spinner' }),
h('span', null, '正在读取钉钉连接状态…'));
}
function EmptyView({ busy, onStart }) {
return h('div', { className: 'ddt-card' },
h('div', { className: 'ddt-cardBody ddt-empty' },
h('div', null,
h('div', { className: 'ddt-stateLabel' },
h('span', { className: 'ddt-dot' }), h('span', null, '尚未接入钉钉机器人')),
h('h3', null, '扫一次码,自动创建并连接机器人'),
h('p', null, '授权由钉钉官方页面完成。扫码账号必须已加入一个企业/组织并有权创建机器人;创建成功后,应用凭据会直接写入 Harness Host。'),
h('div', { className: 'ddt-actions' },
h(Button, { kind: 'primary', onClick: onStart, disabled: busy },
busy ? '正在生成二维码…' : '生成钉钉二维码'))),
h('div', { className: 'ddt-brandMark', 'aria-hidden': 'true' },
h(DingtalkIcon, { size: 68 }))));
}
function QrPanel({ provision, now, busy, onRefresh, onCancel }) {
const [imageFailed, setImageFailed] = React.useState(false);
const source = safeQrSource(provision.qrCodeDataUrl);
const remaining = Math.max(0, provision.expiresAt - now);
const expired = remaining === 0 || provision.status === 'expired';
const duration = Math.max(1, provision.durationMs ?? 10 * 60_000);
const progress = Math.round(Math.min(1, remaining / duration) * 100);
React.useEffect(() => setImageFailed(false), [source]);
return h('div', { className: 'ddt-card' },
h('div', { className: 'ddt-cardBody ddt-qrLayout' },
h('div', { className: 'ddt-qrColumn' },
h('div', { className: 'ddt-qrFrame' },
source && !imageFailed
? h('img', {
src: source,
alt: '用于把钉钉机器人接入 DeepSeek Harness 的一次性二维码',
onError: () => setImageFailed(true),
})
: h('div', { className: 'ddt-qrFallback' }, '二维码图片未就绪,请重新生成。'),
expired ? h('div', { className: 'ddt-expired' }, '二维码已过期\n请重新生成') : null),
h('div', { className: 'ddt-countdown' },
h('div', { className: 'ddt-countdownTop' },
h('span', null, '二维码有效时间'), h('strong', null, formatRemaining(remaining))),
h('div', { className: 'ddt-progress', 'aria-hidden': 'true' },
h('span', { style: { '--ddt-progress': `${progress}%` } })))),
h('div', { className: 'ddt-qrCopy' },
h('div', { className: 'ddt-stateLabel' },
h('span', { className: 'ddt-dot', 'data-tone': expired ? 'error' : 'warning' }),
h('span', null, expired ? '二维码已失效' : '等待钉钉扫码授权')),
h('h3', null, expired ? '重新生成二维码后继续' : '使用钉钉 App 完成机器人授权'),
h('p', null, '扫码账号必须已加入企业/组织。如果钉钉提示尚未加入组织,请在提示页创建组织,或换用已加入组织的账号。'),
h('ol', { className: 'ddt-steps' },
h('li', null, '使用已加入企业/组织的钉钉账号扫描左侧二维码'),
h('li', null, '在授权页点击“一键创建新机器人”'),
h('li', null, '保持本页打开,等待机器人自动连接')),
h('div', { className: 'ddt-brandNotice' },
'钉钉官方授权页目前可能显示 OpenClaw 品牌,这是官方连接器授权页面,不影响机器人接入 DeepSeek Harness。'),
h('div', { className: 'ddt-actions' },
expired
? h(Button, { kind: 'primary', onClick: onRefresh, disabled: busy }, '重新生成二维码')
: null,
!expired ? h(Button, { onClick: onRefresh, disabled: busy }, '换一个二维码') : null,
h(Button, { onClick: onCancel, disabled: busy }, '取消')))));
}
function ProgressPanel({ status, busy, onCancel }) {
const connecting = status === 'connecting';
const creating = status === 'creating';
return h('div', { className: 'ddt-card ddt-loading', 'aria-busy': 'true' },
h('div', { className: 'ddt-spinner' }),
h('h3', null, connecting
? '机器人已创建,正在建立消息连接'
: creating ? '授权已确认,正在创建钉钉机器人' : '正在确认钉钉授权'),
h('p', null, connecting
? '正在检查钉钉 Stream 长连接,成功后会自动显示为在线。'
: '请勿关闭本页,钉钉完成授权后将自动继续。'),
h('div', { className: 'ddt-actions', style: { justifyContent: 'center', marginTop: 14 } },
h(Button, { onClick: onCancel, disabled: busy }, '取消接入')));
}
function ProvisionError({ provision, busy, onRetry, onClose }) {
const error = provision.error ?? {
code: 'DINGTALK_PROVISION_FAILED',
message: '钉钉机器人没有接入完成',
};
return h('div', { className: 'ddt-card' },
h('div', { className: 'ddt-inlineError', role: 'alert' },
h('h3', null, provision.status === 'expired' ? '二维码已过期' : '钉钉机器人没有接入完成'),
h('p', null, error.message),
h('span', { className: 'ddt-errorCode' }, error.code),
h('div', { className: 'ddt-actions' },
h(Button, { kind: 'primary', onClick: onRetry, disabled: busy }, '重新生成二维码'),
h(Button, { onClick: onClose, disabled: busy }, '关闭'))));
}
function checkedTime(value) {
if (!value) return '尚未检查';
try {
return new Intl.DateTimeFormat('zh-CN', {
hour: '2-digit', minute: '2-digit', second: '2-digit',
}).format(new Date(value));
} catch {
return '刚刚';
}
}
function RemoveConfirmation({ account, busy, onConfirm, onCancel }) {
const cancelRef = React.useRef(null);
React.useEffect(() => cancelRef.current?.focus(), []);
return h('div', {
className: 'ddt-confirm',
role: 'alertdialog',
'aria-label': `移除${account.bot.name}`,
onKeyDown: (event) => {
if (event.key === 'Escape' && !busy) onCancel();
},
},
h('strong', null, `从 DeepSeek Harness 移除“${account.bot.name}”?`),
h('p', null, '这会停止消息连接,并删除本机保存的应用凭据、机器人配置及会话映射。钉钉开放平台中的机器人不会被自动删除。'),
h('div', { className: 'ddt-actions' },
h(Button, { ref: cancelRef, onClick: onCancel, disabled: busy }, '保留机器人'),
h(Button, { kind: 'danger', onClick: onConfirm, disabled: busy },
busy ? '正在移除…' : '确认移除接入')));
}
function AccountCard({
account,
busy,
removing,
onReconnect,
onRequestRemove,
onConfirmRemove,
onCancelRemove,
}) {
const state = busy === 'reconnect' ? 'connecting' : account.state;
const tone = account.connected ? 'success' : state === 'error' ? 'error' : 'warning';
const stateLabel = account.connected ? '运行正常' : state === 'connecting' ? '正在连接' : '连接未就绪';
return h('article', { className: 'ddt-card', tabIndex: -1, 'data-bot-id': account.botId },
h('div', { className: 'ddt-cardBody' },
h('div', { className: 'ddt-accountTop' },
h('div', { className: 'ddt-accountIdentity' },
h('div', { className: 'ddt-avatar', 'aria-hidden': 'true' }, h(DingtalkIcon, { size: 29 })),
h('div', null,
h('h3', { title: account.bot.name }, account.bot.name),
h('p', { title: account.bot.clientIdMasked }, account.bot.clientIdMasked))),
h('div', { className: 'ddt-health' },
h('span', { className: 'ddt-dot', 'data-tone': tone }), h('span', null, stateLabel))),
h('dl', { className: 'ddt-metrics' },
h('div', { className: 'ddt-metric' }, h('dt', null, '消息通道'),
h('dd', null, account.connected ? 'Stream 长连接' : '离线')),
h('div', { className: 'ddt-metric' }, h('dt', null, '收到 / 回复'),
h('dd', null, `${account.stats.messagesReceived} / ${account.stats.messagesReplied}`)),
h('div', { className: 'ddt-metric' }, h('dt', null, '最近检查'),
h('dd', null, checkedTime(account.health.lastCheckedAt)))),
h('div', { className: 'ddt-accountFooter' },
h('div', { className: 'ddt-summary' }, account.error?.message ?? account.health.summary),
h('div', { className: 'ddt-actions' },
h(Button, { onClick: onReconnect, disabled: Boolean(busy) },
busy === 'reconnect' ? '检查中…' : account.connected ? '检查连接' : '重试连接'),
h(Button, { kind: 'danger', onClick: onRequestRemove, disabled: Boolean(busy) },
'移除接入')))),
removing ? h(RemoveConfirmation, {
account,
busy: busy === 'delete',
onConfirm: onConfirmRemove,
onCancel: onCancelRemove,
}) : null);
}
function AccountList(props) {
return h('section', null,
h('div', { className: 'ddt-listHeading' },
h('h3', null, '已接入的钉钉机器人'), h('span', null, `${props.bots.length} 个`)),
h('ul', { className: 'ddt-list' }, props.bots.map((account) => h('li', { key: account.botId },
h(AccountCard, {
account,
busy: props.busyByBot[account.botId],
removing: props.removeTarget === account.botId,
onReconnect: () => props.onReconnect(account),
onRequestRemove: () => props.onRequestRemove(account),
onConfirmRemove: () => props.onConfirmRemove(account),
onCancelRemove: props.onCancelRemove,
})))));
}
const EMPTY_TOTALS = Object.freeze({ configured: 0, connected: 0 });
export function DingtalkSettingsTab({ rpcCall }) {
const [model, setModel] = React.useState({
phase: 'loading', bots: [], totals: EMPTY_TOTALS, revision: 0, error: null,
});
const [provision, setProvision] = React.useState(null);
const [busy, setBusy] = React.useState(false);
const [busyByBot, setBusyByBot] = React.useState({});
const [removeTarget, setRemoveTarget] = React.useState(null);
const [notice, setNotice] = React.useState('');
const [now, setNow] = React.useState(() => Date.now());
const addButtonRef = React.useRef(null);
const mountedRef = React.useRef(true);
const statusRequestRef = React.useRef(0);
const noticeFrameRef = React.useRef(null);
const focusFrameRef = React.useRef(null);
React.useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
statusRequestRef.current += 1;
if (noticeFrameRef.current !== null) {
window.cancelAnimationFrame(noticeFrameRef.current);
noticeFrameRef.current = null;
}
if (focusFrameRef.current !== null) {
window.cancelAnimationFrame(focusFrameRef.current);
focusFrameRef.current = null;
}
};
}, []);
React.useEffect(() => installDingtalkStyles(), []);
const announce = React.useCallback((message) => {
if (!mountedRef.current) return;
if (noticeFrameRef.current !== null) {
window.cancelAnimationFrame(noticeFrameRef.current);
noticeFrameRef.current = null;
}
setNotice('');
if (message) {
noticeFrameRef.current = window.requestAnimationFrame(() => {
noticeFrameRef.current = null;
if (mountedRef.current) setNotice(message);
});
}
}, []);
const focusAddButton = React.useCallback(() => {
if (!mountedRef.current) return;
if (focusFrameRef.current !== null) window.cancelAnimationFrame(focusFrameRef.current);
focusFrameRef.current = window.requestAnimationFrame(() => {
focusFrameRef.current = null;
if (mountedRef.current) addButtonRef.current?.focus();
});
}, []);
const invoke = React.useCallback(async (endpoint, payload = {}, signal) => {
if (typeof rpcCall !== 'function') throw new TypeError('钉钉设置页缺少 RPC 连接');
return unwrapRpcResult(await rpcCall(endpoint, payload, signal));
}, [rpcCall]);
const loadStatus = React.useCallback(async ({
signal,
silent = false,
restoreProvisioning = false,
} = {}) => {
if (!mountedRef.current || signal?.aborted) return undefined;
const requestId = statusRequestRef.current + 1;
statusRequestRef.current = requestId;
const canCommit = () => mountedRef.current
&& !signal?.aborted
&& statusRequestRef.current === requestId;
if (!silent && canCommit()) {
setModel((current) => ({ ...current, phase: 'loading', error: null }));
}
try {
const snapshot = normalizeSnapshot(await invoke(DINGTALK_ENDPOINTS.status, {}, signal));
if (!canCommit()) return undefined;
setModel({
phase: 'ready',
bots: snapshot.bots,
totals: snapshot.totals,
revision: snapshot.revision,
error: null,
});
if (restoreProvisioning && snapshot.provisioning) {
setProvision((current) => !current || current.attemptId === snapshot.provisioning.attemptId
? {
...current,
...snapshot.provisioning,
durationMs: current?.durationMs
?? Math.max(1, snapshot.provisioning.expiresAt - Date.now()),
}
: current);
}
return snapshot;
} catch (error) {
if (error?.name === 'AbortError' || !canCommit()) return undefined;
setModel((current) => ({
...current,
phase: silent && current.phase === 'ready' ? 'ready' : 'error',
error: presentError(error),
}));
return undefined;
}
}, [invoke]);
React.useEffect(() => {
const controller = new AbortController();
void loadStatus({ signal: controller.signal, restoreProvisioning: true });
return () => controller.abort();
}, [loadStatus]);
React.useEffect(() => {
if (model.phase !== 'ready') return undefined;
const controller = new AbortController();
let running = false;
const timer = window.setInterval(async () => {
if (running || controller.signal.aborted || !mountedRef.current) return;
running = true;
await loadStatus({
signal: controller.signal,
silent: true,
restoreProvisioning: false,
});
running = false;
}, 15_000);
return () => {
controller.abort();
window.clearInterval(timer);
};
}, [loadStatus, model.phase]);
React.useEffect(() => {
if (!provision || !ACTIVE_PROVISION_STATES.has(provision.status)) return undefined;
const timer = window.setInterval(() => {
if (mountedRef.current) setNow(Date.now());
}, 1_000);
return () => window.clearInterval(timer);
}, [provision?.attemptId, provision?.status]);
const startProvisioning = React.useCallback(async ({ replace = false } = {}) => {
if (!mountedRef.current) return;
setBusy(true);
try {
if (replace && provision?.attemptId) {
await invoke(DINGTALK_ENDPOINTS.cancelProvisioning, {
attemptId: provision.attemptId,
});
if (!mountedRef.current) return;
}
setProvision({ status: 'starting' });
const started = normalizeProvisioning(await invoke(
DINGTALK_ENDPOINTS.beginProvisioning,
{ locale: 'zh-CN' },
));
if (!mountedRef.current) return;
if (!started.qrCodeDataUrl) {
throw new Error('钉钉扫码服务没有返回安全的二维码');
}
setNow(Date.now());
setProvision({
...started,
durationMs: Math.max(1, started.expiresAt - Date.now()),
});
announce('钉钉二维码已生成,请使用钉钉 App 扫描。');
} catch (error) {
if (!mountedRef.current) return;
setProvision({
attemptId: provision?.attemptId,
status: 'failed',
error: presentError(error),
});
} finally {
if (mountedRef.current) setBusy(false);
}
}, [announce, invoke, provision?.attemptId]);
const cancelProvisioning = React.useCallback(async () => {
if (!mountedRef.current) return;
setBusy(true);
try {
if (provision?.attemptId && !['failed', 'expired', 'cancelled'].includes(provision.status)) {
await invoke(DINGTALK_ENDPOINTS.cancelProvisioning, { attemptId: provision.attemptId });
if (!mountedRef.current) return;
}
setProvision(null);
announce('已取消钉钉机器人接入。');
focusAddButton();
} catch (error) {
if (!mountedRef.current) return;
setProvision((current) => ({ ...current, status: 'failed', error: presentError(error) }));
} finally {
if (mountedRef.current) setBusy(false);
}
}, [announce, focusAddButton, invoke, provision?.attemptId, provision?.status]);
React.useEffect(() => {
const attemptId = provision?.attemptId;
if (!attemptId || !ACTIVE_PROVISION_STATES.has(provision.status)) return undefined;
const controller = new AbortController();
let disposed = false;
let timer = null;
const canCommit = () => !disposed && !controller.signal.aborted && mountedRef.current;
const schedule = (delay) => {
if (!canCommit()) return;
if (timer !== null) window.clearTimeout(timer);
timer = window.setTimeout(() => {
timer = null;
if (canCommit()) void poll();
}, delay);
};
const poll = async () => {
try {
const response = await invoke(
DINGTALK_ENDPOINTS.pollProvisioning,
{ attemptId },
controller.signal,
);
if (!canCommit()) return;
const result = normalizeProvisioning(response);
if (result.status === 'connected') {
const snapshot = await loadStatus({
signal: controller.signal,
silent: true,
restoreProvisioning: false,
});
if (!canCommit()) return;
const account = result.botId
? snapshot?.bots.find((bot) => bot.botId === result.botId)
: snapshot?.bots.find((bot) => bot.connected);
if (!account?.connected) {
setProvision((current) => current?.attemptId === attemptId
? { ...current, ...result, status: 'connecting' }
: current);
schedule(result.pollIntervalMs);
return;
}
setProvision(null);
announce(result.alreadyConnected
? '这个钉钉机器人已经接入并保持在线。'
: '钉钉机器人已接入,可以开始发送消息。');
return;
}
if (!canCommit()) return;
setProvision((current) => current?.attemptId === attemptId
? { ...current, ...result, durationMs: current.durationMs }
: current);
if (ACTIVE_PROVISION_STATES.has(result.status)) {
schedule(result.pollIntervalMs);
}
} catch (error) {
if (error?.name === 'AbortError' || !canCommit()) return;
setProvision((current) => current?.attemptId === attemptId
? { ...current, status: 'failed', error: presentError(error) }
: current);
}
};
schedule(provision.pollIntervalMs ?? 3_000);
return () => {
disposed = true;
controller.abort();
if (timer !== null) window.clearTimeout(timer);
timer = null;
};
}, [announce, invoke, loadStatus, provision?.attemptId, provision?.pollIntervalMs, provision?.status]);
const setBotBusy = React.useCallback((botId, operation) => {
if (!mountedRef.current) return;
setBusyByBot((current) => {
const next = { ...current };
if (operation) next[botId] = operation;
else delete next[botId];
return next;
});
}, []);
const runBotAction = React.useCallback(async ({ account, operation, endpoint, payload, success }) => {
if (!mountedRef.current) return undefined;
setBotBusy(account.botId, operation);
try {
await invoke(endpoint, payload);
if (!mountedRef.current) return undefined;
const snapshot = await loadStatus({ silent: true, restoreProvisioning: false });
if (!mountedRef.current) return undefined;
announce(typeof success === 'function' ? success(snapshot) : success);
return snapshot;
} catch (error) {
if (!mountedRef.current) return undefined;
announce(`操作失败:${presentError(error).message}`);
return undefined;
} finally {
if (mountedRef.current) setBotBusy(account.botId, null);
}
}, [announce, invoke, loadStatus, setBotBusy]);
const reconnect = React.useCallback((account) => runBotAction({
account,
operation: 'reconnect',
endpoint: DINGTALK_ENDPOINTS.reconnectBot,
payload: { botId: account.botId },
success: (snapshot) => snapshot?.bots.find((bot) => bot.botId === account.botId)?.connected
? '钉钉连接检查完成。'
: '钉钉仍未连接,插件会继续自动重试。',
}), [runBotAction]);
const remove = React.useCallback(async (account) => {
const snapshot = await runBotAction({
account,
operation: 'delete',
endpoint: DINGTALK_ENDPOINTS.deleteBot,
payload: { botId: account.botId, confirm: true },
success: '钉钉机器人及本机凭据已移除。',
});
if (snapshot && mountedRef.current) setRemoveTarget(null);
}, [runBotAction]);
let provisionView = null;
if (provision?.status === 'starting') {
provisionView = h('div', { className: 'ddt-card ddt-loading', 'aria-busy': 'true' },
h('div', { className: 'ddt-spinner' }), h('span', null, '正在申请钉钉授权二维码…'));
} else if (provision?.status === 'pending') {
provisionView = h(QrPanel, {
provision,
now,
busy,
onRefresh: () => void startProvisioning({ replace: true }),
onCancel: () => void cancelProvisioning(),
});
} else if (['scanned', 'authorizing', 'creating', 'connecting'].includes(provision?.status)) {
provisionView = h(ProgressPanel, {
status: provision.status,
busy,
onCancel: () => void cancelProvisioning(),
});
} else if (provision && ['failed', 'expired', 'cancelled'].includes(provision.status)) {
provisionView = h(ProvisionError, {
provision,
busy,
onRetry: () => void startProvisioning({ replace: Boolean(provision.attemptId) }),
onClose: () => void cancelProvisioning(),
});
}
return h('section', { className: 'ddt-page', 'aria-label': '钉钉设置' },
h(Heading, {
totals: model.totals,
adding: Boolean(provision),
busy,
onAdd: () => void startProvisioning(),
addButtonRef,
}),
h('div', { className: 'ddt-visuallyHidden', role: 'status', 'aria-live': 'polite' }, notice),
model.error && model.phase === 'ready'
? h('div', { className: 'ddt-statusNotice', role: 'alert' }, `状态刷新失败:${model.error.message}`)
: null,
model.phase === 'loading'
? h(LoadingView)
: model.phase === 'error'
? h('div', { className: 'ddt-card' },
h('div', { className: 'ddt-inlineError', role: 'alert' },
h('h3', null, '无法读取钉钉机器人状态'),
h('p', null, model.error?.message ?? '请稍后重试'),
h(Button, { onClick: () => void loadStatus() }, '重新读取')))
: h(React.Fragment, null,
provisionView,
model.bots.length === 0 && !provision
? h(EmptyView, { busy, onStart: () => void startProvisioning() })
: null,
model.bots.length > 0
? h(AccountList, {
bots: model.bots,
busyByBot,
removeTarget,
onReconnect: (account) => void reconnect(account),
onRequestRemove: (account) => setRemoveTarget(account.botId),
onConfirmRemove: (account) => void remove(account),
onCancelRemove: () => setRemoveTarget(null),
})
: null));
}
export function apply(ctx) {
ctx.effect(() => installDingtalkStyles(), 'dingtalk-settings: install client styles');
const rpcCall = (endpoint, payload, signal) =>
ctx.connection.rpc.call(DINGTALK_RPC_CHANNEL, endpoint, payload, signal);
ctx.slots.inject('settings.plugins.tab', () => ctx.slots.register({
name: 'settings.plugins.tab',
id: 'dingtalk',
order: 40,
label: '钉钉',
inject: () => ({ rpcCall }),
}, DingtalkSettingsTab));
}

View file

@ -0,0 +1,141 @@
export const DINGTALK_STYLE_ID = 'xmanrui-dsh-dingtalk-settings';
const CSS = String.raw`
.ddt-page {
--ddt-accent: #1677ff;
--ddt-accent-deep: #0958d9;
--ddt-accent-wash: #eaf3ff;
--ddt-success: var(--dsw-alias-state-success-primary, #20a162);
--ddt-warning: var(--dsw-alias-state-warning-primary, #d97706);
--ddt-error: var(--dsw-alias-state-error-primary, #d54941);
width: 100%;
max-width: 880px;
display: flex;
flex-direction: column;
gap: 18px;
padding: 2px 0 28px;
container-type: inline-size;
color: var(--dsw-alias-label-primary, #1f2329);
box-sizing: border-box;
}
.ddt-page *, .ddt-page *::before, .ddt-page *::after { box-sizing: border-box; }
.ddt-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 20px; }
.ddt-headingCopy { min-width: 0; }
.ddt-heading h2, .ddt-heading p, .ddt-card h3, .ddt-card h4, .ddt-card p { margin: 0; }
.ddt-eyebrow { margin-bottom: 3px; color: var(--dsw-alias-label-tertiary, #8f959e); font-size: 12px; font-weight: 650; letter-spacing: .08em; text-transform: uppercase; }
.ddt-heading h2 { font-size: 20px; line-height: 28px; font-weight: 680; }
.ddt-heading p { margin-top: 5px; color: var(--dsw-alias-label-secondary, #646a73); font-size: 13px; line-height: 20px; white-space: nowrap; }
.ddt-tools, .ddt-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
.ddt-tools { justify-content: flex-end; }
.ddt-badge { min-height: 30px; display: inline-flex; align-items: center; gap: 7px; padding: 0 11px; border-radius: 999px; color: var(--dsw-alias-label-secondary, #646a73); background: var(--dsw-alias-fill-secondary, #f2f3f5); font-size: 12px; white-space: nowrap; }
.ddt-dot { width: 8px; height: 8px; flex: none; border-radius: 50%; background: #aeb3bb; }
.ddt-dot[data-tone="success"] { background: var(--ddt-success); box-shadow: 0 0 0 3px color-mix(in srgb, var(--ddt-success) 14%, transparent); }
.ddt-dot[data-tone="warning"] { background: var(--ddt-warning); }
.ddt-dot[data-tone="error"] { background: var(--ddt-error); }
.ddt-button { min-height: 34px; display: inline-flex; align-items: center; justify-content: center; gap: 7px; padding: 0 13px; border: 1px solid var(--dsw-alias-line-border, #dfe1e5); border-radius: 8px; color: var(--dsw-alias-label-primary, #1f2329); background: var(--dsw-alias-bg-body, #fff); font: inherit; font-size: 13px; font-weight: 560; text-decoration: none; cursor: pointer; transition: border-color .15s ease, background .15s ease, transform .15s ease; }
.ddt-button:hover:not(:disabled) { border-color: #aeb3bb; background: var(--dsw-alias-fill-tertiary, #f7f8fa); }
.ddt-button:active:not(:disabled) { transform: translateY(1px); }
.ddt-button:focus-visible { outline: 2px solid color-mix(in srgb, var(--ddt-accent) 70%, white); outline-offset: 2px; }
.ddt-button:disabled { cursor: not-allowed; opacity: .55; }
.ddt-button[data-kind="primary"] { color: #fff; border-color: var(--ddt-accent); background: var(--ddt-accent); }
.ddt-button[data-kind="primary"]:hover:not(:disabled) { border-color: var(--ddt-accent-deep); background: var(--ddt-accent-deep); }
.ddt-button[data-kind="danger"] { color: var(--ddt-error); }
.ddt-button[data-kind="quiet"] { min-height: 30px; padding: 0 10px; border-color: transparent; background: transparent; }
.ddt-card { overflow: hidden; border: 1px solid var(--dsw-alias-line-border, #e5e6eb); border-radius: 14px; background: var(--dsw-alias-bg-body, #fff); box-shadow: 0 1px 2px rgb(31 35 41 / 3%); }
.ddt-cardBody { padding: 24px; }
.ddt-empty { min-height: 230px; display: grid; grid-template-columns: minmax(0, 1fr) 180px; align-items: center; gap: 30px; }
.ddt-empty h3 { margin: 8px 0; font-size: 18px; }
.ddt-empty p { max-width: 560px; color: var(--dsw-alias-label-secondary, #646a73); line-height: 1.65; }
.ddt-empty .ddt-actions { margin-top: 20px; }
.ddt-brandMark { width: 110px; height: 110px; display: grid; place-items: center; justify-self: center; border-radius: 28px; color: #fff; background: linear-gradient(145deg, #2997ff, var(--ddt-accent)); box-shadow: 0 18px 45px rgb(22 119 255 / 23%); }
.ddt-brandMark svg { filter: drop-shadow(0 3px 8px rgb(0 35 96 / 16%)); }
.ddt-qrLayout { display: grid; grid-template-columns: 300px minmax(0, 1fr); gap: 34px; align-items: start; }
.ddt-qrColumn { display: flex; flex-direction: column; align-items: center; gap: 12px; }
.ddt-qrFrame { position: relative; width: min(270px, 100%); aspect-ratio: 1; display: grid; place-items: center; overflow: hidden; padding: 10px; border: 1px solid var(--dsw-alias-line-border, #e5e6eb); border-radius: 16px; background: #fff; }
.ddt-qrFrame::before { content: ''; position: absolute; inset: 6px; border: 1px solid rgb(22 119 255 / 10%); border-radius: 11px; pointer-events: none; }
.ddt-qrFrame img { display: block; width: 100%; height: 100%; object-fit: contain; }
.ddt-qrFallback { padding: 24px; color: #646a73; text-align: center; }
.ddt-expired { position: absolute; inset: 0; display: grid; place-items: center; padding: 30px; color: #fff; text-align: center; font-weight: 650; white-space: pre-line; background: rgb(31 35 41 / 76%); backdrop-filter: blur(3px); }
.ddt-countdown { width: min(270px, 100%); color: var(--dsw-alias-label-secondary, #646a73); font-size: 12px; }
.ddt-countdownTop { display: flex; justify-content: space-between; margin-bottom: 6px; }
.ddt-countdown strong { color: var(--dsw-alias-label-primary, #1f2329); font-variant-numeric: tabular-nums; }
.ddt-progress { height: 4px; overflow: hidden; border-radius: 99px; background: #eef0f3; }
.ddt-progress span { display: block; width: var(--ddt-progress); height: 100%; background: var(--ddt-accent); transition: width .2s linear; }
.ddt-stateLabel { display: inline-flex; align-items: center; gap: 8px; color: var(--dsw-alias-label-secondary, #646a73); font-size: 12px; font-weight: 600; }
.ddt-qrCopy { min-width: 0; overflow-wrap: anywhere; }
.ddt-qrCopy h3 { margin: 9px 0 8px; font-size: 18px; }
.ddt-qrCopy > p { color: var(--dsw-alias-label-secondary, #646a73); line-height: 1.65; }
.ddt-steps { margin: 18px 0 16px; padding: 0; list-style: none; counter-reset: ddt-step; }
.ddt-steps li { position: relative; min-height: 28px; padding: 3px 0 3px 36px; color: var(--dsw-alias-label-secondary, #646a73); font-size: 13px; line-height: 22px; counter-increment: ddt-step; }
.ddt-steps li::before { content: counter(ddt-step); position: absolute; left: 0; top: 1px; width: 26px; height: 26px; display: grid; place-items: center; border-radius: 8px; color: var(--ddt-accent-deep); background: var(--ddt-accent-wash); font-size: 12px; font-weight: 700; }
.ddt-brandNotice { margin: 0 0 18px; padding: 10px 12px; border-left: 3px solid #91caff; border-radius: 0 8px 8px 0; color: var(--dsw-alias-label-secondary, #646a73); background: #f5f9ff; font-size: 12px; line-height: 1.55; }
.ddt-loading { padding: 38px; color: var(--dsw-alias-label-secondary, #646a73); text-align: center; }
.ddt-loading h3 { margin: 0 0 7px; color: var(--dsw-alias-label-primary, #1f2329); font-size: 17px; }
.ddt-loading p { line-height: 1.6; }
.ddt-spinner { width: 24px; height: 24px; margin: 0 auto 13px; border: 3px solid #e6e8eb; border-top-color: var(--ddt-accent); border-radius: 50%; animation: ddt-spin .8s linear infinite; }
.ddt-statusNotice, .ddt-inlineError { display: flex; align-items: flex-start; gap: 10px; padding: 13px 15px; border: 1px solid color-mix(in srgb, var(--ddt-error) 28%, transparent); border-radius: 10px; color: var(--ddt-error); background: color-mix(in srgb, var(--ddt-error) 7%, transparent); font-size: 13px; }
.ddt-inlineError { flex-direction: column; padding: 22px; }
.ddt-inlineError h3 { font-size: 17px; }
.ddt-inlineError p { line-height: 1.55; }
.ddt-errorCode { font: 11px ui-monospace, SFMono-Regular, monospace; opacity: .8; }
.ddt-listHeading { display: flex; align-items: center; justify-content: space-between; margin: 2px 0 9px; }
.ddt-listHeading h3 { margin: 0; font-size: 14px; }
.ddt-listHeading span { color: var(--dsw-alias-label-tertiary, #8f959e); font-size: 12px; }
.ddt-list { display: grid; gap: 12px; margin: 0; padding: 0; list-style: none; }
.ddt-accountTop { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
.ddt-accountIdentity { min-width: 0; display: flex; align-items: center; gap: 12px; }
.ddt-avatar { width: 42px; height: 42px; display: grid; place-items: center; flex: none; border-radius: 12px; color: #fff; background: linear-gradient(145deg, #2997ff, var(--ddt-accent)); }
.ddt-accountIdentity h3 { overflow: hidden; font-size: 15px; text-overflow: ellipsis; white-space: nowrap; }
.ddt-accountIdentity p { margin-top: 4px; color: var(--dsw-alias-label-secondary, #646a73); font: 12px ui-monospace, SFMono-Regular, monospace; }
.ddt-health { display: inline-flex; align-items: center; gap: 7px; color: var(--dsw-alias-label-secondary, #646a73); font-size: 12px; white-space: nowrap; }
.ddt-metrics { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; margin: 20px 0; }
.ddt-metric { min-width: 0; padding: 12px; border-radius: 9px; background: var(--dsw-alias-fill-tertiary, #f7f8fa); }
.ddt-metric dt { color: var(--dsw-alias-label-tertiary, #8f959e); font-size: 11px; }
.ddt-metric dd { overflow: hidden; margin: 5px 0 0; font-size: 13px; text-overflow: ellipsis; white-space: nowrap; }
.ddt-accountFooter { display: flex; align-items: center; justify-content: space-between; gap: 15px; padding-top: 16px; border-top: 1px solid var(--dsw-alias-line-divider, #eef0f3); }
.ddt-summary { color: var(--dsw-alias-label-secondary, #646a73); font-size: 12px; }
.ddt-confirm { padding: 18px 24px; border-top: 1px solid color-mix(in srgb, var(--ddt-error) 25%, transparent); background: color-mix(in srgb, var(--ddt-error) 5%, transparent); }
.ddt-confirm strong { display: block; margin-bottom: 6px; font-size: 14px; }
.ddt-confirm p { color: var(--dsw-alias-label-secondary, #646a73); font-size: 12px; line-height: 1.55; }
.ddt-confirm .ddt-actions { margin-top: 13px; }
.ddt-visuallyHidden { position: absolute !important; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
@keyframes ddt-spin { to { transform: rotate(360deg); } }
@container (max-width: 680px) {
.ddt-heading { flex-direction: column; align-items: stretch; }
.ddt-tools { width: 100%; flex-wrap: nowrap; gap: 6px; }
.ddt-tools .ddt-badge { min-height: 34px; padding-inline: 8px; }
.ddt-tools .ddt-button { flex: none; padding-inline: 10px; white-space: nowrap; }
.ddt-empty { grid-template-columns: minmax(0, 1fr); }
.ddt-brandMark { display: none; }
.ddt-qrLayout { grid-template-columns: minmax(0, 1fr); justify-items: center; gap: 24px; }
.ddt-qrColumn { width: 100%; min-width: 0; }
.ddt-qrCopy { width: 100%; }
.ddt-metrics { gap: 8px; }
.ddt-metric { padding: 10px; }
}
@media (max-width: 720px) {
.ddt-heading, .ddt-accountTop, .ddt-accountFooter { flex-direction: column; align-items: stretch; }
.ddt-heading p { white-space: normal; }
.ddt-tools { justify-content: flex-start; }
.ddt-empty { grid-template-columns: minmax(0, 1fr); }
.ddt-brandMark { display: none; }
.ddt-qrLayout { grid-template-columns: minmax(0, 1fr); justify-items: center; }
.ddt-qrCopy { width: 100%; }
.ddt-cardBody { padding: 20px; }
}
@media (prefers-reduced-motion: reduce) {
.ddt-page *, .ddt-page *::before, .ddt-page *::after { animation-duration: .01ms !important; transition-duration: .01ms !important; }
}
`;
export function installDingtalkStyles() {
if (typeof document === 'undefined') return () => {};
const existing = document.querySelector(`style[data-plugin-css="${DINGTALK_STYLE_ID}"]`);
if (existing) return () => {};
const style = document.createElement('style');
style.dataset.plugin = '@xmanrui/dsh-dingtalk';
style.dataset.pluginCss = DINGTALK_STYLE_ID;
style.textContent = CSS;
document.head.appendChild(style);
return () => style.remove();
}

View file

@ -1,7 +1,7 @@
import * as React from 'react';
import { DINGTALK_RPC_CHANNEL } from '@xmanrui/dsh-dingtalk/client-api';
import { DingtalkSettingsTab } from '@xmanrui/dsh-dingtalk/client-source';
import { DINGTALK_RPC_CHANNEL } from './channels/dingtalk/api.js';
import { DingtalkSettingsTab } from './channels/dingtalk/index.js';
import { FeishuSettingsTab } from './channels/feishu/index.js';
import { FEISHU_RPC_CHANNEL } from './channels/feishu/api.js';
import { installFeishuStyles } from './channels/feishu/styles.js';

View file

@ -0,0 +1,130 @@
const DEFAULT_RETRY_DELAYS_MS = Object.freeze([250, 1_000, 3_000, 5_000, 10_000, 30_000]);
function retryDelays(value) {
if (!Array.isArray(value) || value.length === 0) return [...DEFAULT_RETRY_DELAYS_MS];
const valid = value.filter((delay) => Number.isFinite(delay) && delay >= 0);
return valid.length > 0 ? valid : [...DEFAULT_RETRY_DELAYS_MS];
}
export class ConnectionSupervisor {
#controller;
#harness;
#logger;
#retryDelays;
#healthyIntervalMs;
#setTimeout;
#clearTimeout;
#timer = null;
#running = null;
#retryIndex = 0;
#closed = false;
#started = false;
#ready;
#resolveReady;
constructor({
controller,
harness,
logger = console,
retryDelaysMs,
healthyIntervalMs = 15_000,
setTimeoutImpl = setTimeout,
clearTimeoutImpl = clearTimeout,
}) {
if (!controller || typeof controller.initialize !== 'function' || typeof controller.status !== 'function') {
throw new TypeError('ConnectionSupervisor requires a controller');
}
if (!harness || typeof harness.ensureRunning !== 'function') {
throw new TypeError('ConnectionSupervisor requires a Harness client');
}
this.#controller = controller;
this.#harness = harness;
this.#logger = logger;
this.#retryDelays = retryDelays(retryDelaysMs);
this.#healthyIntervalMs = Number.isFinite(healthyIntervalMs) && healthyIntervalMs >= 0
? healthyIntervalMs
: 15_000;
this.#setTimeout = setTimeoutImpl;
this.#clearTimeout = clearTimeoutImpl;
this.#ready = new Promise((resolve) => {
this.#resolveReady = resolve;
});
}
get ready() {
return this.#ready;
}
start() {
if (this.#started || this.#closed) return this;
this.#started = true;
this.#schedule(0);
return this;
}
async close() {
if (this.#closed) return;
this.#closed = true;
if (this.#timer !== null) this.#clearTimeout(this.#timer);
this.#timer = null;
await this.#running?.catch(() => undefined);
this.#resolveReady?.(null);
this.#resolveReady = null;
}
#schedule(delayMs) {
if (this.#closed) return;
this.#timer = this.#setTimeout(() => {
this.#timer = null;
void this.#run();
}, delayMs);
this.#timer?.unref?.();
}
async #run() {
if (this.#closed || this.#running) return;
const operation = this.#reconcile();
this.#running = operation;
try {
await operation;
} finally {
if (this.#running === operation) this.#running = null;
}
}
async #reconcile() {
try {
await this.#harness.ensureRunning();
if (this.#closed) return;
const status = await this.#controller.initialize();
if (this.#closed) return;
this.#resolveReady?.(status);
this.#resolveReady = null;
const { configured, connected } = status.totals;
if (connected < configured) {
const delayMs = this.#retryDelays[Math.min(this.#retryIndex, this.#retryDelays.length - 1)];
this.#retryIndex += 1;
this.#logger.warn?.(
`[dsh-dingtalk] ${connected}/${configured} bots connected; retrying in ${delayMs}ms`,
);
this.#schedule(delayMs);
return;
}
this.#retryIndex = 0;
this.#schedule(this.#healthyIntervalMs);
} catch (error) {
if (this.#closed) return;
const delayMs = this.#retryDelays[Math.min(this.#retryIndex, this.#retryDelays.length - 1)];
this.#retryIndex += 1;
this.#logger.warn?.(
`[dsh-dingtalk] connection reconciliation failed; retrying in ${delayMs}ms`,
error,
);
this.#schedule(delayMs);
}
}
}
export function createConnectionSupervisor(options) {
return new ConnectionSupervisor(options);
}

View file

@ -0,0 +1,32 @@
import { createProductionController } from './production.mjs';
import { installDingtalkRpc } from './rpc.mjs';
export const name = 'dsh-dingtalk-host';
export const inject = ['connection', 'credentials', 'webServer'];
export async function apply(ctx, config = {}) {
if (config?.controller) return installDingtalkRpc(ctx, config.controller, config.rpcOptions);
const production = await createProductionController(ctx, config, config.internals);
const disposeRpc = installDingtalkRpc(ctx, production.controller, config.rpcOptions);
ctx.effect(() => async () => {
await production.close();
}, 'dsh-dingtalk: close bot connections');
return disposeRpc;
}
export function createDingtalkHostPlugin(config) {
return Object.freeze({ name, inject, apply: (ctx) => apply(ctx, config) });
}
export { createConnectionSupervisor, ConnectionSupervisor } from './connection-supervisor.mjs';
export { createProductionController } from './production.mjs';
export {
DINGTALK_ENDPOINTS,
DINGTALK_RPC_CHANNEL,
DINGTALK_RPC_ENDPOINTS,
createDingtalkRpcHandler,
installDingtalkRpc,
} from './rpc.mjs';
export { DingtalkController } from '../../../../src/channels/dingtalk/dingtalk-controller.mjs';
export { DingtalkRuntime } from '../../../../src/channels/dingtalk/dingtalk-runtime.mjs';

View file

@ -0,0 +1,122 @@
import { unlink } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join, resolve } from 'node:path';
import { DingtalkConfigStore } from '../../../../src/channels/dingtalk/config-store.mjs';
import { DingtalkDeviceAuth } from '../../../../src/channels/dingtalk/device-auth.mjs';
import { DingtalkController } from '../../../../src/channels/dingtalk/dingtalk-controller.mjs';
import { DingtalkRuntime } from '../../../../src/channels/dingtalk/dingtalk-runtime.mjs';
import { HarnessClient } from '../../../../src/channels/dingtalk/harness-client.mjs';
import { DingtalkStateStore } from '../../../../src/channels/dingtalk/state-store.mjs';
import { createConnectionSupervisor } from './connection-supervisor.mjs';
function harnessOrigin(webServer, configured) {
if (configured !== undefined) return new URL(configured);
const port = webServer?.port;
if (!Number.isInteger(port) || port < 1 || port > 65_535) {
throw new Error('dsh-dingtalk requires an initialized DSH webServer port');
}
return new URL(`http://127.0.0.1:${port}`);
}
function pluginPaths(config) {
const dshHome = resolve(config.dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh'));
const root = resolve(config.dataDir ?? join(dshHome, 'integrations', 'dsh-dingtalk'));
return {
root,
config: resolve(config.configPath ?? join(root, 'config.json')),
bots: resolve(config.botsDir ?? join(root, 'bots')),
};
}
export async function createProductionController(ctx, config = {}, internals = {}) {
if (!ctx?.credentials) throw new TypeError('dsh-dingtalk requires ctx.credentials');
if (!ctx?.webServer) throw new TypeError('dsh-dingtalk requires ctx.webServer');
const ConfigStore = internals.ConfigStore ?? DingtalkConfigStore;
const DeviceAuth = internals.DeviceAuth ?? DingtalkDeviceAuth;
const StateStore = internals.StateStore ?? DingtalkStateStore;
const Harness = internals.HarnessClient ?? HarnessClient;
const Controller = internals.Controller ?? DingtalkController;
const Runtime = internals.Runtime ?? DingtalkRuntime;
const createSupervisor = internals.createConnectionSupervisor ?? createConnectionSupervisor;
const logger = typeof ctx.logger === 'function'
? ctx.logger('dsh-dingtalk')
: (ctx.logger ?? console);
const paths = pluginPaths(config);
const configStore = await new ConfigStore(paths.config).load();
const deviceAuth = internals.deviceAuth ?? new DeviceAuth({
baseUrl: config.registrationBaseUrl,
});
const stateStores = new Map();
const statePath = (botId) => resolve(paths.bots, botId, 'state.json');
const stateFor = async (botId) => {
let state = stateStores.get(botId);
if (!state) {
state = await new StateStore(statePath(botId)).load();
stateStores.set(botId, state);
}
return state;
};
const harness = new Harness({
baseUrl: harnessOrigin(ctx.webServer, config.harnessBaseUrl),
workspace: resolve(config.workspace ?? process.cwd()),
agentPreset: config.agentPreset ?? 'standard',
autostart: false,
dshBin: config.dshBin ?? 'dsh',
});
const controller = new Controller({
deviceAuth,
credentials: ctx.credentials,
configStore,
logger,
createRuntime: async ({ botId, config: botConfig, clientSecret }) => {
const state = await stateFor(botId);
return new Runtime({
config: botConfig,
clientSecret,
harness,
state,
replyTimeoutMs: config.replyTimeoutMs ?? 600_000,
maxMessageChars: config.maxMessageChars ?? 4_000,
connectTimeoutMs: config.connectTimeoutMs ?? 15_000,
logger: {
error: (...args) => logger.error?.(`[${botId}]`, ...args),
warn: (...args) => logger.warn?.(`[${botId}]`, ...args),
info: (...args) => logger.info?.(`[${botId}]`, ...args),
debug: (...args) => logger.debug?.(`[${botId}]`, ...args),
},
});
},
deleteState: async ({ botId }) => {
const state = stateStores.get(botId);
stateStores.delete(botId);
if (state && typeof state.remove === 'function') {
await state.remove();
return;
}
try {
await unlink(statePath(botId));
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
}
},
});
const supervisor = createSupervisor({
controller,
harness,
logger,
retryDelaysMs: config.retryDelaysMs,
healthyIntervalMs: config.healthyIntervalMs,
}).start();
return {
controller,
ready: supervisor.ready,
async close() {
await supervisor.close();
await controller.close();
harness.stopManagedProcess();
},
};
}

View file

@ -0,0 +1,221 @@
import QRCode from 'qrcode';
export const DINGTALK_RPC_CHANNEL = '/dingtalk';
export const DINGTALK_ENDPOINTS = Object.freeze({
status: 'connection.status',
beginProvisioning: 'provision.begin',
pollProvisioning: 'provision.poll',
cancelProvisioning: 'provision.cancel',
reconnectBot: 'bot.reconnect',
deleteBot: 'bot.delete',
approveSender: 'bot.sender.approve',
revokeSender: 'bot.sender.revoke',
});
export const DINGTALK_RPC_ENDPOINTS = Object.freeze(Object.values(DINGTALK_ENDPOINTS));
const FORBIDDEN_PUBLIC_KEYS = new Set([
'clientSecret',
'client_secret',
'deviceCode',
'device_code',
'secretRef',
'staffId',
'senderStaffId',
'verificationUrl',
'verificationUri',
'userCode',
]);
function isRecord(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function exactKeys(value, allowed) {
return isRecord(value) && Object.keys(value).every((key) => allowed.includes(key));
}
function validId(value) {
return typeof value === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(value);
}
function payloadFailure(endpoint, payload) {
if (!isRecord(payload)) return 'Payload must be an object.';
if (endpoint === DINGTALK_ENDPOINTS.status) {
return exactKeys(payload, []) ? null : 'connection.status does not accept fields.';
}
if (endpoint === DINGTALK_ENDPOINTS.beginProvisioning) {
return exactKeys(payload, ['locale']) && (payload.locale === undefined || payload.locale === 'zh-CN')
? null
: 'provision.begin received unsupported fields.';
}
if ([DINGTALK_ENDPOINTS.pollProvisioning, DINGTALK_ENDPOINTS.cancelProvisioning].includes(endpoint)) {
return exactKeys(payload, ['attemptId']) && validId(payload.attemptId)
? null
: `${endpoint} requires an attemptId.`;
}
if (endpoint === DINGTALK_ENDPOINTS.reconnectBot) {
return exactKeys(payload, ['botId']) && validId(payload.botId)
? null
: 'bot.reconnect requires a botId.';
}
if (endpoint === DINGTALK_ENDPOINTS.deleteBot) {
return exactKeys(payload, ['botId', 'confirm']) && validId(payload.botId) && payload.confirm === true
? null
: 'bot.delete requires a botId and confirm=true.';
}
if (endpoint === DINGTALK_ENDPOINTS.approveSender) {
return exactKeys(payload, ['botId', 'requestId', 'confirm'])
&& validId(payload.botId)
&& validId(payload.requestId)
&& payload.confirm === true
? null
: 'bot.sender.approve requires botId, requestId, and confirm=true.';
}
if (endpoint === DINGTALK_ENDPOINTS.revokeSender) {
return exactKeys(payload, ['botId', 'senderKey', 'confirm'])
&& validId(payload.botId)
&& validId(payload.senderKey)
&& payload.confirm === true
? null
: 'bot.sender.revoke requires botId, senderKey, and confirm=true.';
}
return 'Unknown DingTalk endpoint.';
}
function badRequest(message) {
return { ok: false, error: { code: 'bad-request', message } };
}
function cancelled() {
return { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } };
}
function internalFailure() {
return {
ok: false,
error: { code: 'dingtalk-operation-failed', message: '钉钉操作失败,请稍后重试。' },
};
}
function sanitizePublic(value) {
if (Array.isArray(value)) return value.map(sanitizePublic);
if (!isRecord(value)) return value;
const safe = {};
for (const [key, child] of Object.entries(value)) {
if (!FORBIDDEN_PUBLIC_KEYS.has(key)) safe[key] = sanitizePublic(child);
}
return safe;
}
async function qrDataUrl(value) {
return QRCode.toDataURL(value, {
type: 'image/png',
errorCorrectionLevel: 'M',
margin: 2,
width: 320,
});
}
async function withEncodedQr(value, encodeQr) {
if (!value || typeof value.verificationUrl !== 'string') return sanitizePublic(value);
return sanitizePublic({
...value,
qrCodeDataUrl: await encodeQr(value.verificationUrl),
});
}
async function publicStatus(status, encodeQr) {
const value = structuredClone(status);
if (value?.provisioning) {
value.provisioning = await withEncodedQr(value.provisioning, encodeQr);
}
return sanitizePublic(value);
}
function assertController(controller) {
for (const method of [
'status',
'startProvisioning',
'registrationStatus',
'cancelProvisioning',
'reconnectBot',
'deleteBot',
'approveSender',
'revokeSender',
]) {
if (typeof controller?.[method] !== 'function') {
throw new TypeError(`A complete DingTalk controller is required (${method})`);
}
}
}
export function createDingtalkRpcHandler(controller, { encodeQr = qrDataUrl } = {}) {
assertController(controller);
const qrCache = new Map();
const cachedEncode = (url) => {
let encoded = qrCache.get(url);
if (!encoded) {
if (qrCache.size >= 16) qrCache.delete(qrCache.keys().next().value);
encoded = Promise.resolve().then(() => encodeQr(url));
qrCache.set(url, encoded);
}
return encoded;
};
return async (endpoint, payload, signal) => {
if (signal?.aborted) return cancelled();
if (!DINGTALK_RPC_ENDPOINTS.includes(endpoint)) return badRequest('Unknown DingTalk endpoint.');
const invalid = payloadFailure(endpoint, payload);
if (invalid) return badRequest(invalid);
try {
let value;
if (endpoint === DINGTALK_ENDPOINTS.status) {
value = await publicStatus(await controller.status(), cachedEncode);
} else if (endpoint === DINGTALK_ENDPOINTS.beginProvisioning) {
const started = await controller.startProvisioning({ signal });
if (signal?.aborted) {
await controller.cancelProvisioning(started.attemptId);
return cancelled();
}
value = await withEncodedQr(started, cachedEncode);
} else if (endpoint === DINGTALK_ENDPOINTS.pollProvisioning) {
const current = await controller.registrationStatus(payload.attemptId);
if (!current) return badRequest('The provisioning attempt no longer exists.');
value = await withEncodedQr(current, cachedEncode);
} else if (endpoint === DINGTALK_ENDPOINTS.cancelProvisioning) {
value = await controller.cancelProvisioning(payload.attemptId);
if (!value) return badRequest('The provisioning attempt no longer exists.');
value = sanitizePublic(value);
} else if (endpoint === DINGTALK_ENDPOINTS.reconnectBot) {
value = await publicStatus(await controller.reconnectBot(payload.botId), cachedEncode);
} else if (endpoint === DINGTALK_ENDPOINTS.deleteBot) {
value = await publicStatus(await controller.deleteBot(payload.botId), cachedEncode);
} else if (endpoint === DINGTALK_ENDPOINTS.approveSender) {
value = await publicStatus(
await controller.approveSender(payload.botId, payload.requestId),
cachedEncode,
);
} else {
value = await publicStatus(
await controller.revokeSender(payload.botId, payload.senderKey),
cachedEncode,
);
}
return signal?.aborted ? cancelled() : { ok: true, value };
} catch {
return signal?.aborted ? cancelled() : internalFailure();
}
};
}
export function installDingtalkRpc(ctx, controller, options) {
if (!ctx?.connection?.rpc || typeof ctx.connection.rpc.handle !== 'function') {
throw new TypeError('DSH Host Connection RPC is required');
}
return ctx.connection.rpc.handle(
DINGTALK_RPC_CHANNEL,
createDingtalkRpcHandler(controller, options),
{ authority: 'loopback' },
);
}

View file

@ -0,0 +1,167 @@
const DEFAULT_RETRY_DELAYS_MS = Object.freeze([250, 1_000, 3_000, 5_000, 10_000, 30_000]);
function safeDelay(value, fallback) {
return Number.isFinite(value) && value >= 0 ? value : fallback;
}
function safeRetryDelays(value) {
if (!Array.isArray(value) || value.length === 0) return [...DEFAULT_RETRY_DELAYS_MS];
const delays = value.map((delay) => safeDelay(delay, -1)).filter((delay) => delay >= 0);
return delays.length > 0 ? delays : [...DEFAULT_RETRY_DELAYS_MS];
}
function totals(status) {
const configured = Number.isInteger(status?.totals?.configured)
? status.totals.configured
: (Array.isArray(status?.bots) ? status.bots.length : 0);
const connected = Number.isInteger(status?.totals?.connected)
? status.totals.connected
: (Array.isArray(status?.bots)
? status.bots.filter((bot) => bot?.connected === true).length
: 0);
return { configured, connected };
}
/**
* Starts bot connections only after the in-process Harness HTTP API is ready,
* then periodically reconciles failed/offline bots. Timers never keep the Host
* alive on their own and shutdown waits for an in-flight reconciliation.
*/
export class ConnectionSupervisor {
#controller;
#harness;
#logger;
#retryDelaysMs;
#healthyIntervalMs;
#setTimeout;
#clearTimeout;
#timer = null;
#running = null;
#retryIndex = 0;
#started = false;
#closed = false;
#ready;
#resolveReady;
constructor({
controller,
harness,
logger = console,
retryDelaysMs,
healthyIntervalMs = 15_000,
setTimeoutImpl = setTimeout,
clearTimeoutImpl = clearTimeout,
}) {
if (!controller
|| typeof controller.initialize !== 'function'
|| typeof controller.status !== 'function') {
throw new TypeError('ConnectionSupervisor requires a controller');
}
if (!harness || typeof harness.ensureRunning !== 'function') {
throw new TypeError('ConnectionSupervisor requires a Harness client');
}
this.#controller = controller;
this.#harness = harness;
this.#logger = logger;
this.#retryDelaysMs = safeRetryDelays(retryDelaysMs);
this.#healthyIntervalMs = safeDelay(healthyIntervalMs, 15_000);
this.#setTimeout = setTimeoutImpl;
this.#clearTimeout = clearTimeoutImpl;
this.#ready = new Promise((resolve) => {
this.#resolveReady = resolve;
});
}
get ready() {
return this.#ready;
}
start() {
if (this.#started || this.#closed) return this;
this.#started = true;
this.#schedule(0);
return this;
}
async close() {
if (this.#closed) return;
this.#closed = true;
if (this.#timer !== null) {
this.#clearTimeout(this.#timer);
this.#timer = null;
}
await this.#running?.catch(() => undefined);
this.#resolveReady?.(null);
this.#resolveReady = null;
}
#schedule(delayMs) {
if (this.#closed) return;
this.#timer = this.#setTimeout(() => {
this.#timer = null;
void this.#run();
}, delayMs);
this.#timer?.unref?.();
}
async #run() {
if (this.#closed || this.#running) return;
const operation = this.#reconcile();
this.#running = operation;
try {
await operation;
} finally {
if (this.#running === operation) this.#running = null;
}
}
async #reconcile() {
try {
await this.#harness.ensureRunning();
} catch (error) {
if (this.#closed) return;
this.#retry('Harness Host is not ready', error);
return;
}
if (this.#closed) return;
try {
await this.#controller.initialize();
if (this.#closed) return;
const status = this.#controller.status();
this.#resolveReady?.(status);
this.#resolveReady = null;
const current = totals(status);
if (current.connected < current.configured) {
const delay = this.#retryDelaysMs[Math.min(this.#retryIndex, this.#retryDelaysMs.length - 1)];
this.#retryIndex += 1;
this.#logger.warn?.(
`[dsh-feishu] ${current.connected}/${current.configured} bots connected; retrying automatically in ${delay}ms`,
);
this.#schedule(delay);
return;
}
this.#retryIndex = 0;
this.#schedule(this.#healthyIntervalMs);
} catch (error) {
if (this.#closed) return;
this.#retry('Bot connection reconciliation failed', error);
}
}
#retry(message, error) {
const delay = this.#retryDelaysMs[Math.min(this.#retryIndex, this.#retryDelaysMs.length - 1)];
this.#retryIndex += 1;
this.#logger.warn?.(
`[dsh-feishu] ${message}; retrying automatically in ${delay}ms`,
error,
);
this.#schedule(delay);
}
}
export function createConnectionSupervisor(options) {
return new ConnectionSupervisor(options);
}

View file

@ -0,0 +1,172 @@
const ACTIVE_REGISTRATION_STATES = new Set([
'starting',
'qr_ready',
'polling',
'slow_down',
'domain_switched',
]);
function credentialResult(result) {
const appId = result?.client_id ?? result?.appId;
const appSecret = result?.client_secret ?? result?.appSecret;
if (typeof appId !== 'string' || appId.length === 0
|| typeof appSecret !== 'string' || appSecret.length === 0) {
throw new TypeError('Feishu registration returned invalid credentials');
}
return {
appId,
appSecret,
userInfo: result?.user_info ?? result?.userInfo,
};
}
async function readConnectionStatus(connectionManager) {
if (typeof connectionManager.status !== 'function') return {};
return await connectionManager.status();
}
function isConnected(status) {
if (status?.connected === true) return true;
return status?.ready === true
&& status?.feishuLongConnectionState === 'connected'
&& status?.harnessReachable === true;
}
/**
* Minimal orchestration boundary between QR provisioning and the live bot.
*
* `createProvisioningManager` receives the only callback that can observe the
* App Secret. The callback persists credentials and starts the long-lived
* connection before the provisioning manager may report `succeeded`.
*/
export class ProvisioningBackedController {
#credentialStore;
#connectionManager;
#registrationOptions;
#manager;
#knownConfigured = false;
#lastError = null;
constructor({
createProvisioningManager,
credentialStore,
connectionManager,
registrationOptions = {},
} = {}) {
if (typeof createProvisioningManager !== 'function') {
throw new TypeError('createProvisioningManager is required');
}
if (!credentialStore
|| typeof credentialStore.save !== 'function'
|| typeof credentialStore.clear !== 'function') {
throw new TypeError('credentialStore.save/clear are required');
}
if (!connectionManager
|| typeof connectionManager.connect !== 'function'
|| typeof connectionManager.disconnect !== 'function') {
throw new TypeError('connectionManager.connect/disconnect are required');
}
if (registrationOptions === null
|| typeof registrationOptions !== 'object'
|| Array.isArray(registrationOptions)) {
throw new TypeError('registrationOptions must be an object');
}
this.#credentialStore = credentialStore;
this.#connectionManager = connectionManager;
this.#registrationOptions = structuredClone(registrationOptions);
this.#manager = createProvisioningManager({
onCredentials: (result) => this.#acceptCredentials(result),
});
if (!this.#manager
|| typeof this.#manager.start !== 'function'
|| typeof this.#manager.status !== 'function'
|| typeof this.#manager.cancel !== 'function') {
throw new TypeError('The provisioning manager must implement start/status/cancel');
}
}
async startRegistration() {
this.#lastError = null;
await this.#manager.start(structuredClone(this.#registrationOptions));
return this.status();
}
async cancelRegistration() {
await this.#manager.cancel();
return this.status();
}
async disconnect() {
await this.#manager.cancel();
await this.#connectionManager.disconnect();
try {
await this.#credentialStore.clear();
this.#knownConfigured = false;
this.#lastError = null;
} catch {
// Do not reflect a credential provider's error text across the RPC
// boundary. It may include a backend path or secret reference detail.
this.#lastError = {
code: 'credential_removal_failed',
message: 'Unable to remove the Feishu credentials.',
};
}
return this.status();
}
async status() {
const registration = await this.#manager.status();
const connection = await readConnectionStatus(this.#connectionManager);
const connected = isConnected(connection);
let configured = this.#knownConfigured;
if (typeof this.#credentialStore.configured === 'function') {
try {
configured = await this.#credentialStore.configured();
} catch {
configured = this.#knownConfigured;
}
}
let phase = 'unconfigured';
if (connected) phase = 'connected';
else if (ACTIVE_REGISTRATION_STATES.has(registration?.state)) phase = 'registering';
else if (registration?.state === 'saving') phase = 'connecting';
else if (this.#lastError || registration?.state === 'error') phase = 'error';
else if (configured) phase = 'disconnected';
return {
phase,
connected,
configured,
registration,
connection,
error: this.#lastError ?? registration?.error ?? null,
};
}
async close() {
await this.#manager.cancel();
await this.#connectionManager.disconnect();
}
async #acceptCredentials(result) {
const credentials = credentialResult(result);
try {
await this.#credentialStore.save(credentials);
this.#knownConfigured = true;
await this.#connectionManager.connect(credentials);
this.#lastError = null;
} catch {
this.#lastError = {
code: 'connection_failed',
message: 'The bot was created, but its connection could not be started.',
};
throw new Error('Unable to activate the Feishu connection.');
}
}
}
export function createProvisioningBackedController(options) {
return new ProvisioningBackedController(options);
}

View file

@ -0,0 +1,84 @@
/**
* Credential references owned by the Feishu Host plugin. They deliberately
* use DSH's credential provider instead of plugin settings, so the browser's
* configuration plane can only observe configured/source metadata.
*/
export const FEISHU_APP_ID_REF = 'DSH_FEISHU_APP_ID';
export const FEISHU_APP_SECRET_REF = 'DSH_FEISHU_APP_SECRET';
function assertNonEmptyString(value, label) {
if (typeof value !== 'string' || value.length === 0) {
throw new TypeError(`${label} must be a non-empty string`);
}
return value;
}
async function restore(provider, ref, previous) {
try {
if (previous?.value) await provider.set(ref, previous.value);
else await provider.unset(ref);
} catch {
// Preserve the original write failure. The provider remains the source
// of truth and will report the partial state through describe().
}
}
/**
* Adapt the real DSH `ctx.credentials` seam to the small interface consumed
* by the Feishu controller. Secret values only travel Host-to-Host here.
*
* @param {{resolve(Function), describe(Function), set(Function), unset(Function)}} provider
* @param {{appIdRef?: string, appSecretRef?: string}} options
*/
export function createDshCredentialStore(provider, options = {}) {
if (!provider
|| typeof provider.resolve !== 'function'
|| typeof provider.describe !== 'function'
|| typeof provider.set !== 'function'
|| typeof provider.unset !== 'function') {
throw new TypeError('A DSH credential provider is required');
}
const appIdRef = options.appIdRef ?? FEISHU_APP_ID_REF;
const appSecretRef = options.appSecretRef ?? FEISHU_APP_SECRET_REF;
return Object.freeze({
async save({ appId, appSecret }) {
const nextId = assertNonEmptyString(appId, 'Feishu App ID');
const nextSecret = assertNonEmptyString(appSecret, 'Feishu App Secret');
const [previousId, previousSecret] = await Promise.all([
provider.resolve(appIdRef),
provider.resolve(appSecretRef),
]);
try {
// Store the secret first. An App ID without its matching secret must
// never be treated as a usable integration.
await provider.set(appSecretRef, nextSecret);
await provider.set(appIdRef, nextId);
} catch {
await restore(provider, appSecretRef, previousSecret);
await restore(provider, appIdRef, previousId);
throw new Error('Unable to store the Feishu credentials.');
}
},
async clear() {
const outcomes = await Promise.allSettled([
provider.unset(appIdRef),
provider.unset(appSecretRef),
]);
if (outcomes.some((outcome) => outcome.status === 'rejected')) {
throw new Error('Unable to remove the Feishu credentials.');
}
},
async configured() {
const [appId, appSecret] = await Promise.all([
provider.describe(appIdRef),
provider.describe(appSecretRef),
]);
return appId.configured === true && appSecret.configured === true;
},
});
}

View file

@ -0,0 +1,66 @@
import { createProvisioningBackedController } from './controller.mjs';
import { createProductionController } from './production.mjs';
import { installFeishuRpc } from './rpc.mjs';
export const name = 'dsh-feishu-host';
export const inject = ['connection', 'credentials', 'webServer'];
function controllerFrom(ctx, config) {
if (config?.controller) return config.controller;
if (typeof config?.createController === 'function') return config.createController();
if (typeof config?.createProvisioningManager === 'function') {
return createProvisioningBackedController(config);
}
// Cordis deliberately throws when a plugin reads an undeclared service,
// even through optional chaining. Production uses the explicit services in
// `inject`; test/programmatic controllers must therefore come from config.
return undefined;
}
/**
* Cordis/DSH Host plugin entry. Production composition may supply an owned
* controller service; tests and embedded distributions may inject one through
* config without changing the Connection RPC boundary.
*/
export async function apply(ctx, config = {}) {
const controller = controllerFrom(ctx, config);
if (controller) return installFeishuRpc(ctx, controller);
const production = await createProductionController(ctx, config);
const disposeRpc = installFeishuRpc(ctx, production.controller);
ctx.effect(() => async () => {
await production.close();
}, 'dsh-feishu: close controller and live connection');
return disposeRpc;
}
/** Create a programmatic plugin module with dependencies closed over. */
export function createFeishuHostPlugin(config) {
return Object.freeze({
name,
inject,
apply: (ctx) => apply(ctx, config),
});
}
export {
ProvisioningBackedController,
createProvisioningBackedController,
} from './controller.mjs';
export { createProductionController } from './production.mjs';
export { ConnectionSupervisor, createConnectionSupervisor } from './connection-supervisor.mjs';
export { MultiBotDshFeishuController } from '../../../../src/channels/feishu/multi-bot-controller.mjs';
export {
FEISHU_APP_ID_REF,
FEISHU_APP_SECRET_REF,
createDshCredentialStore,
} from './credential-store.mjs';
export {
FEISHU_ENDPOINTS,
FEISHU_MULTI_ENDPOINTS,
FEISHU_RPC_CHANNEL,
FEISHU_RPC_ENDPOINTS,
createFeishuRpcHandler,
installFeishuRpc,
toPublicFeishuStatus,
} from './rpc.mjs';

View file

@ -0,0 +1,138 @@
import { homedir } from 'node:os';
import { join, resolve } from 'node:path';
import { unlink } from 'node:fs/promises';
import * as Lark from '@larksuiteoapi/node-sdk';
import { createConnectionSupervisor } from './connection-supervisor.mjs';
import { verifyFeishuApp } from '../../../../src/channels/feishu/feishu-app.mjs';
import { FeishuRuntime } from '../../../../src/channels/feishu/feishu-runtime.mjs';
import { HarnessClient } from '../../../../src/channels/feishu/harness-client.mjs';
import {
LEGACY_FEISHU_SECRET_REF,
PluginConfigStore,
} from '../../../../src/channels/feishu/plugin-config-store.mjs';
import { MultiBotDshFeishuController } from '../../../../src/channels/feishu/multi-bot-controller.mjs';
import { StateStore } from '../../../../src/channels/feishu/state-store.mjs';
function harnessOrigin(webServer, configured) {
if (configured !== undefined) return new URL(configured);
const port = webServer?.port;
if (!Number.isInteger(port) || port < 1 || port > 65_535) {
throw new Error('dsh-feishu requires an initialized DSH webServer port');
}
// Even when DSH listens on all interfaces, its own plugin talks through the
// loopback authority accepted by Connection's request-trust fence.
return new URL(`http://127.0.0.1:${port}`);
}
function pluginPaths(config) {
const dshHome = resolve(config.dshHome
?? process.env.DSH_HOME
?? join(homedir(), '.dsh'));
const root = resolve(config.dataDir ?? join(dshHome, 'integrations', 'dsh-feishu'));
return {
root,
config: resolve(config.configPath ?? join(root, 'config.json')),
legacyState: resolve(config.statePath ?? join(root, 'state.json')),
bots: resolve(config.botsDir ?? join(root, 'bots')),
};
}
/**
* Assemble the production controller from DSH Host services and local plugin
* classes. No bridge process or environment App credentials are required.
*/
export async function createProductionController(ctx, config = {}, internals = {}) {
if (!ctx?.credentials) throw new TypeError('dsh-feishu requires ctx.credentials');
if (!ctx?.webServer) throw new TypeError('dsh-feishu requires ctx.webServer');
const lark = internals.lark ?? Lark;
const Controller = internals.Controller ?? MultiBotDshFeishuController;
const ConfigStore = internals.ConfigStore ?? PluginConfigStore;
const SessionStateStore = internals.StateStore ?? StateStore;
const Harness = internals.HarnessClient ?? HarnessClient;
const Runtime = internals.FeishuRuntime ?? FeishuRuntime;
const verifyApp = internals.verifyFeishuApp ?? verifyFeishuApp;
const createSupervisor = internals.createConnectionSupervisor ?? createConnectionSupervisor;
const logger = typeof ctx.logger === 'function'
? ctx.logger('dsh-feishu')
: (ctx.logger ?? console);
const paths = pluginPaths(config);
const configStore = await new ConfigStore(paths.config).load();
// State is lazy per bot. A corrupt legacy file can therefore fail only the
// migrated bot and cannot prevent healthy v2 bots from starting.
const stateStores = new Map();
const statePathFor = (botConfig) => !botConfig.id
|| !botConfig.secretRef
|| botConfig.secretRef === LEGACY_FEISHU_SECRET_REF
? paths.legacyState
: resolve(paths.bots, botConfig.id, 'state.json');
const stateFor = async (botConfig) => {
const stateKey = botConfig.id ?? '__legacy__';
let state = stateStores.get(stateKey);
if (!state) {
state = await new SessionStateStore(statePathFor(botConfig)).load();
stateStores.set(stateKey, state);
}
return state;
};
const harness = new Harness({
baseUrl: harnessOrigin(ctx.webServer, config.harnessBaseUrl),
workspace: resolve(config.workspace ?? process.cwd()),
agentPreset: config.agentPreset ?? 'standard',
// This plugin is already hosted by a running DSH process. Starting a
// second DSH would create a competing server and lifecycle.
autostart: false,
dshBin: config.dshBin ?? 'dsh',
});
const controller = new Controller({
registerApp: (options) => lark.registerApp(options),
verifyApp,
credentials: ctx.credentials,
configStore,
createRuntime: async ({ botId, config: botConfig, appSecret }) => {
const state = await stateFor(botConfig);
return new Runtime({
lark,
appId: botConfig.appId,
appSecret,
domain: botConfig.domain,
ownerOpenIds: botConfig.ownerOpenIds ?? [botConfig.ownerOpenId],
harness,
state,
replyTimeoutMs: config.replyTimeoutMs ?? 600_000,
logger: {
error: (...args) => logger.error?.(`[${botId ?? botConfig.id}]`, ...args),
warn: (...args) => logger.warn?.(`[${botId ?? botConfig.id}]`, ...args),
info: (...args) => logger.info?.(`[${botId ?? botConfig.id}]`, ...args),
debug: (...args) => logger.debug?.(`[${botId ?? botConfig.id}]`, ...args),
},
});
},
deleteState: async ({ botId, config: botConfig }) => {
stateStores.delete(botId);
try {
await unlink(statePathFor(botConfig));
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
}
},
});
const supervisor = createSupervisor({
controller,
harness,
logger,
retryDelaysMs: config.retryDelaysMs,
healthyIntervalMs: config.healthyIntervalMs,
}).start();
return {
controller,
ready: supervisor.ready,
async close() {
await supervisor.close();
await controller.close();
harness.stopManagedProcess();
},
};
}

View file

@ -0,0 +1,434 @@
import QRCode from 'qrcode';
import {
FEISHU_ENDPOINTS,
FEISHU_RPC_CHANNEL,
} from '../../../client/channels/feishu/api.js';
export { FEISHU_ENDPOINTS, FEISHU_RPC_CHANNEL };
export const FEISHU_MULTI_ENDPOINTS = Object.freeze({
reconnectBot: 'bot.reconnect',
disconnectBot: 'bot.disconnect',
deleteBot: 'bot.delete',
});
export const FEISHU_RPC_ENDPOINTS = Object.freeze([
...new Set([...Object.values(FEISHU_ENDPOINTS), ...Object.values(FEISHU_MULTI_ENDPOINTS)]),
]);
const REGISTRATION_STATES = new Set([
'idle', 'starting', 'qr_ready', 'polling', 'slow_down',
'domain_switched', 'saving', 'succeeded', 'expired', 'cancelled', 'error',
]);
const SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/;
const PUBLIC_ERROR_MESSAGES = Object.freeze({
abort: 'Registration was cancelled.',
access_denied: 'Registration was denied.',
expired_token: 'The registration QR code expired.',
invalid_credentials: 'Feishu returned invalid app credentials.',
credentials_callback_failed: 'Unable to activate the Feishu connection.',
registration_failed: 'Unable to register the Feishu app.',
connection_failed: 'The bot was created, but its connection could not be started.',
credential_removal_failed: 'Unable to remove the Feishu credentials.',
state_cleanup_failed: 'Unable to remove the bot session data. Please retry.',
deletion_pending: 'Bot deletion is incomplete. Retry removal to finish cleanup.',
missing_credentials: 'The bot credentials are missing. Delete it and scan again.',
});
const POLL_STATUS_BY_REGISTRATION = Object.freeze({
idle: 'pending', starting: 'pending', qr_ready: 'pending', polling: 'pending',
slow_down: 'pending', domain_switched: 'pending', saving: 'connecting',
succeeded: 'connected', expired: 'expired', cancelled: 'failed', error: 'failed',
});
function isPlainObject(value) {
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
function hasOnlyKeys(value, allowed) {
return isPlainObject(value)
&& Reflect.ownKeys(value).every((key) => typeof key === 'string' && allowed.has(key));
}
function finiteNumber(value) {
return Number.isFinite(value) ? value : undefined;
}
function safeOpaqueId(value) {
return typeof value === 'string' && SAFE_ID.test(value);
}
function publicError(error) {
if (!error || typeof error !== 'object') return null;
const code = typeof error.code === 'string' && Object.hasOwn(PUBLIC_ERROR_MESSAGES, error.code)
? error.code
: 'registration_failed';
return { code, message: PUBLIC_ERROR_MESSAGES[code] };
}
function publicRegistration(registration) {
if (!registration || typeof registration !== 'object') return { state: 'idle', attempt: 0 };
const state = REGISTRATION_STATES.has(registration.state) ? registration.state : 'error';
const attempt = safeOpaqueId(registration.attempt)
? registration.attempt
: (finiteNumber(registration.attempt) ?? 0);
const result = { state, attempt };
const updatedAt = finiteNumber(registration.updatedAt);
const expiresAt = finiteNumber(registration.expiresAt);
const remainingSeconds = finiteNumber(registration.remainingSeconds);
const pollIntervalSeconds = finiteNumber(registration.pollIntervalSeconds);
if (updatedAt !== undefined) result.updatedAt = updatedAt;
if (typeof registration.qrCodeUrl === 'string' && registration.qrCodeUrl.length > 0) {
result.qrCodeUrl = registration.qrCodeUrl;
}
if (expiresAt !== undefined) result.expiresAt = expiresAt;
if (remainingSeconds !== undefined) result.remainingSeconds = remainingSeconds;
if (pollIntervalSeconds !== undefined) result.pollIntervalSeconds = pollIntervalSeconds;
if (safeOpaqueId(registration.botId)) result.botId = registration.botId;
const error = publicError(registration.error);
if (error) result.error = error;
return result;
}
function connectionFacts(connection) {
const source = connection && typeof connection === 'object' ? connection : {};
const connected = source.connected === true
|| (source.ready === true
&& source.feishuLongConnectionState === 'connected'
&& source.harnessReachable === true);
return {
connected,
ready: source.ready === true,
harnessReachable: source.harnessReachable === true,
};
}
function publicBot(bot) {
const source = bot && typeof bot === 'object' ? bot : {};
const result = {
name: typeof source.name === 'string' && source.name.length > 0 ? source.name : '飞书机器人',
};
if (typeof source.avatarUrl === 'string') result.avatarUrl = source.avatarUrl;
if (typeof source.appIdMasked === 'string') result.appIdMasked = source.appIdMasked;
if (typeof source.tenantName === 'string') result.tenantName = source.tenantName;
if (source.domain === 'feishu' || source.domain === 'lark') result.domain = source.domain;
if (typeof source.activated === 'boolean' || typeof source.activated === 'number') {
result.activated = source.activated;
}
return result;
}
function publicHealth(status, connected) {
if (connected) return { status: 'healthy', summary: '长连接运行正常', lastCheckedAt: Date.now() };
if (status?.configured === true) {
return { status: 'offline', summary: '机器人尚未连接', lastCheckedAt: Date.now() };
}
return { status: 'offline', summary: '尚未接入飞书机器人', lastCheckedAt: Date.now() };
}
function connectionState(status, registration, connected) {
if (connected) return 'connected';
if (status?.phase === 'error' || registration.state === 'error') return 'error';
if (status?.phase === 'connecting' || registration.state === 'saving') return 'connecting';
if (status?.phase === 'registering'
|| ['starting', 'qr_ready', 'polling', 'slow_down', 'domain_switched'].includes(registration.state)) {
return 'provisioning';
}
return 'disconnected';
}
async function qrCodeDataUrl(verificationUrl) {
return QRCode.toDataURL(verificationUrl, {
errorCorrectionLevel: 'M', margin: 1, width: 320, type: 'image/png',
});
}
async function publicProvisioning(registration, encodeQr) {
if (!registration.qrCodeUrl) return undefined;
return {
attemptId: String(registration.attempt),
verificationUrl: registration.qrCodeUrl,
qrCodeDataUrl: await encodeQr(registration.qrCodeUrl),
expiresAt: registration.expiresAt ?? Date.now() + (5 * 60_000),
pollIntervalMs: Math.max(800, Math.min(10_000, (registration.pollIntervalSeconds ?? 1.8) * 1000)),
};
}
function publicBotEntry(entry) {
const source = entry && typeof entry === 'object' ? entry : {};
if (!safeOpaqueId(source.botId)) return null;
const facts = connectionFacts(source.connection);
const connected = source.connected === true || facts.connected;
const registration = { state: 'idle' };
const result = {
botId: source.botId,
state: connectionState(source, registration, connected),
connected,
configured: source.configured === true,
bot: publicBot(source.bot),
health: publicHealth(source, connected),
};
const error = publicError(source.error);
if (error) result.error = error;
return result;
}
/** Exact redacted browser contract consumed by the Feishu settings client. */
export async function toPublicFeishuStatus(status, { encodeQr = qrCodeDataUrl } = {}) {
const source = status && typeof status === 'object' ? status : {};
const registration = publicRegistration(source.registration);
const facts = connectionFacts(source.connection);
const connected = source.connected === true || facts.connected;
const provisioning = await publicProvisioning(registration, encodeQr);
const error = publicError(source.error) ?? registration.error ?? null;
const bots = Array.isArray(source.bots)
? source.bots.map(publicBotEntry).filter(Boolean)
: [];
const snapshot = {
schemaVersion: source.schemaVersion === 2 ? 2 : 1,
revision: Number.isSafeInteger(source.revision) && source.revision >= 0 ? source.revision : 0,
state: connectionState(source, registration, connected),
connected,
configured: source.configured === true,
bot: publicBot(source.bot),
health: publicHealth(source, connected),
bots,
totals: {
configured: bots.length || (source.configured === true ? 1 : 0),
connected: bots.length ? bots.filter((bot) => bot.connected).length : (connected ? 1 : 0),
},
};
if (provisioning) snapshot.provisioning = provisioning;
if (error) snapshot.error = error;
return snapshot;
}
function badRequest(message) {
return { ok: false, error: { code: 'bad-request', message, details: { issues: [] } } };
}
function cancelled() {
return { ok: false, error: { code: 'cancelled', message: 'The Feishu request was cancelled.', details: {} } };
}
function internalFailure() {
return { ok: false, error: { code: 'internal', message: 'The Feishu integration operation failed.', details: {} } };
}
function validPayload(endpoint, payload) {
if (endpoint === FEISHU_ENDPOINTS.status) {
return hasOnlyKeys(payload, new Set()) ? null : 'This endpoint accepts an empty payload only.';
}
if (endpoint === FEISHU_ENDPOINTS.testConnection) {
return hasOnlyKeys(payload, new Set()) ? null : 'This endpoint accepts an empty payload only.';
}
if (endpoint === FEISHU_ENDPOINTS.beginProvisioning) {
if (!hasOnlyKeys(payload, new Set(['locale', 'replaceAttemptId']))) {
return 'Provisioning accepts locale and replaceAttemptId only.';
}
if (payload.locale !== undefined && payload.locale !== 'zh-CN') return 'The provisioning locale must be zh-CN.';
if (payload.replaceAttemptId !== undefined && !safeOpaqueId(payload.replaceAttemptId)) {
return 'replaceAttemptId must be a valid opaque id.';
}
return null;
}
if (endpoint === FEISHU_ENDPOINTS.pollProvisioning
|| endpoint === FEISHU_ENDPOINTS.cancelProvisioning) {
return hasOnlyKeys(payload, new Set(['attemptId'])) && safeOpaqueId(payload.attemptId)
? null
: 'A single valid attemptId is required.';
}
if (endpoint === FEISHU_ENDPOINTS.disconnect) {
return hasOnlyKeys(payload, new Set(['removeCredentials'])) && payload.removeCredentials === true
? null
: 'Disconnect requires removeCredentials=true.';
}
if (endpoint === FEISHU_MULTI_ENDPOINTS.reconnectBot
|| endpoint === FEISHU_MULTI_ENDPOINTS.disconnectBot) {
return hasOnlyKeys(payload, new Set(['botId'])) && safeOpaqueId(payload.botId)
? null
: 'A single valid botId is required.';
}
if (endpoint === FEISHU_MULTI_ENDPOINTS.deleteBot) {
return hasOnlyKeys(payload, new Set(['botId', 'confirm']))
&& safeOpaqueId(payload.botId) && payload.confirm === true
? null
: 'Deleting a bot requires a valid botId and confirm=true.';
}
return 'Unknown Feishu endpoint.';
}
function abortableDelay(milliseconds, signal) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason ?? new Error('aborted'));
return;
}
const timer = setTimeout(done, milliseconds);
timer.unref?.();
function done() {
signal?.removeEventListener('abort', aborted);
resolve();
}
function aborted() {
clearTimeout(timer);
reject(signal.reason ?? new Error('aborted'));
}
signal?.addEventListener('abort', aborted, { once: true });
});
}
async function statusForRegistration(controller, attemptId) {
if (typeof controller.registrationStatus === 'function') {
return controller.registrationStatus(attemptId);
}
return controller.status();
}
async function waitForQr(controller, initial, attemptId, signal) {
let current = initial;
const deadline = Date.now() + 15_000;
for (;;) {
const registration = publicRegistration(current?.registration);
if (registration.qrCodeUrl) return current;
if (['error', 'expired', 'cancelled'].includes(registration.state)) {
throw new Error('Provisioning stopped before the QR code was ready.');
}
if (Date.now() >= deadline) throw new Error('Provisioning QR code timed out.');
await abortableDelay(50, signal);
current = await statusForRegistration(controller, attemptId);
if (!current) throw new Error('The provisioning attempt is no longer active.');
}
}
function sameAttempt(status, attemptId) {
return String(publicRegistration(status?.registration).attempt) === attemptId;
}
function pollStatus(status) {
const registration = publicRegistration(status?.registration);
if (registration.state === 'succeeded') {
const connected = registration.botId
&& (status?.connected === true || connectionFacts(status?.connection).connected);
return connected ? 'connected' : 'connecting';
}
return POLL_STATUS_BY_REGISTRATION[registration.state] ?? 'failed';
}
function assertController(controller) {
if (!controller
|| typeof controller.status !== 'function'
|| typeof controller.startRegistration !== 'function'
|| typeof controller.cancelRegistration !== 'function'
|| typeof controller.disconnect !== 'function') {
throw new TypeError('A Feishu controller with status/start/cancel/disconnect is required');
}
}
/** DSH rc.6 handler: (endpoint, payload, signal) => Promise<RpcResult>. */
export function createFeishuRpcHandler(controller, { encodeQr = qrCodeDataUrl } = {}) {
assertController(controller);
const qrCache = new Map();
const attemptQr = new Map();
const cachedEncodeQr = (url) => {
let encoded = qrCache.get(url);
if (!encoded) {
if (qrCache.size >= 32) qrCache.delete(qrCache.keys().next().value);
encoded = Promise.resolve().then(() => encodeQr(url));
qrCache.set(url, encoded);
}
return encoded;
};
return async (endpoint, payload, signal) => {
if (signal?.aborted) return cancelled();
if (!FEISHU_RPC_ENDPOINTS.includes(endpoint)) return badRequest('Unknown Feishu endpoint.');
const payloadFailure = validPayload(endpoint, payload);
if (payloadFailure) return badRequest(payloadFailure);
try {
let value;
if (endpoint === FEISHU_ENDPOINTS.status) {
value = await toPublicFeishuStatus(await controller.status(), { encodeQr: cachedEncodeQr });
} else if (endpoint === FEISHU_ENDPOINTS.beginProvisioning) {
if (payload.replaceAttemptId) {
await controller.cancelRegistration(payload.replaceAttemptId);
}
const started = await controller.startRegistration({ locale: payload.locale });
const attemptId = String(publicRegistration(started?.registration).attempt);
const ready = await waitForQr(controller, started, attemptId, signal);
value = (await toPublicFeishuStatus(ready, { encodeQr: cachedEncodeQr })).provisioning;
if (!value) throw new Error('Provisioning did not produce a QR code.');
attemptQr.set(attemptId, value.verificationUrl);
} else if (endpoint === FEISHU_ENDPOINTS.pollProvisioning) {
const current = await statusForRegistration(controller, payload.attemptId);
if (!current || !sameAttempt(current, payload.attemptId)) {
return badRequest('The provisioning attempt is no longer active.');
}
const registration = publicRegistration(current.registration);
const connection = await toPublicFeishuStatus(current, { encodeQr: cachedEncodeQr });
value = {
status: pollStatus(current),
...(registration.botId ? { botId: registration.botId } : {}),
...(connection.provisioning ? { provisioning: connection.provisioning } : {}),
...(registration.botId && connection.connected ? { connection } : {}),
...(connection.error ? { message: connection.error.message } : {}),
};
if (['connected', 'expired', 'failed'].includes(value.status)) {
const url = attemptQr.get(payload.attemptId);
if (url) qrCache.delete(url);
attemptQr.delete(payload.attemptId);
}
} else if (endpoint === FEISHU_ENDPOINTS.cancelProvisioning) {
const current = await statusForRegistration(controller, payload.attemptId);
if (!current || !sameAttempt(current, payload.attemptId)) {
return badRequest('The provisioning attempt is no longer active.');
}
const multi = typeof controller.registrationStatus === 'function';
const registration = publicRegistration(current.registration);
if (!multi && registration.state === 'saving') await controller.disconnect();
else await controller.cancelRegistration(payload.attemptId);
const url = attemptQr.get(payload.attemptId);
if (url) qrCache.delete(url);
attemptQr.delete(payload.attemptId);
value = { status: 'failed', message: 'Registration was cancelled.' };
} else if (endpoint === FEISHU_ENDPOINTS.testConnection) {
const current = await controller.status();
const alreadyConnected = current?.connected === true
|| connectionFacts(current?.connection).connected;
const checked = alreadyConnected || typeof controller.reconnect !== 'function'
? current
: await controller.reconnect();
value = await toPublicFeishuStatus(checked, { encodeQr: cachedEncodeQr });
} else if (endpoint === FEISHU_ENDPOINTS.disconnect) {
value = await toPublicFeishuStatus(await controller.disconnect(), { encodeQr: cachedEncodeQr });
} else if (endpoint === FEISHU_MULTI_ENDPOINTS.reconnectBot) {
if (typeof controller.reconnectBot !== 'function') throw new Error('Multi-bot reconnect is unavailable');
value = await toPublicFeishuStatus(await controller.reconnectBot(payload.botId), { encodeQr: cachedEncodeQr });
} else if (endpoint === FEISHU_MULTI_ENDPOINTS.disconnectBot) {
if (typeof controller.disconnectBot !== 'function') throw new Error('Multi-bot disconnect is unavailable');
value = await toPublicFeishuStatus(await controller.disconnectBot(payload.botId), { encodeQr: cachedEncodeQr });
} else {
if (typeof controller.deleteBot !== 'function') throw new Error('Multi-bot delete is unavailable');
value = await toPublicFeishuStatus(await controller.deleteBot(payload.botId), { encodeQr: cachedEncodeQr });
}
if (signal?.aborted) return cancelled();
return { ok: true, value };
} catch {
return signal?.aborted ? cancelled() : internalFailure();
}
};
}
/** Register the loopback-only `/feishu` logical channel. */
export function installFeishuRpc(ctx, controller, options) {
if (!ctx?.connection?.rpc || typeof ctx.connection.rpc.handle !== 'function') {
throw new TypeError('DSH Host Connection RPC is required');
}
return ctx.connection.rpc.handle(
FEISHU_RPC_CHANNEL,
createFeishuRpcHandler(controller, options),
{ authority: 'loopback' },
);
}

View file

@ -0,0 +1,127 @@
const DEFAULT_RETRY_DELAYS_MS = Object.freeze([250, 1_000, 3_000, 5_000, 10_000, 30_000]);
function retryDelays(value) {
if (!Array.isArray(value) || value.length === 0) return [...DEFAULT_RETRY_DELAYS_MS];
const valid = value.filter((delay) => Number.isFinite(delay) && delay >= 0);
return valid.length > 0 ? valid : [...DEFAULT_RETRY_DELAYS_MS];
}
export class ConnectionSupervisor {
#controller;
#harness;
#logger;
#retryDelays;
#healthyIntervalMs;
#setTimeout;
#clearTimeout;
#timer = null;
#running = null;
#retryIndex = 0;
#closed = false;
#started = false;
#ready;
#resolveReady;
constructor({
controller,
harness,
logger = console,
retryDelaysMs,
healthyIntervalMs = 15_000,
setTimeoutImpl = setTimeout,
clearTimeoutImpl = clearTimeout,
}) {
if (!controller || typeof controller.initialize !== 'function' || typeof controller.status !== 'function') {
throw new TypeError('ConnectionSupervisor requires a controller');
}
if (!harness || typeof harness.ensureRunning !== 'function') {
throw new TypeError('ConnectionSupervisor requires a Harness client');
}
this.#controller = controller;
this.#harness = harness;
this.#logger = logger;
this.#retryDelays = retryDelays(retryDelaysMs);
this.#healthyIntervalMs = Number.isFinite(healthyIntervalMs) && healthyIntervalMs >= 0
? healthyIntervalMs
: 15_000;
this.#setTimeout = setTimeoutImpl;
this.#clearTimeout = clearTimeoutImpl;
this.#ready = new Promise((resolve) => {
this.#resolveReady = resolve;
});
}
get ready() {
return this.#ready;
}
start() {
if (this.#started || this.#closed) return this;
this.#started = true;
this.#schedule(0);
return this;
}
async close() {
if (this.#closed) return;
this.#closed = true;
if (this.#timer !== null) this.#clearTimeout(this.#timer);
this.#timer = null;
await this.#running?.catch(() => undefined);
this.#resolveReady?.(null);
this.#resolveReady = null;
}
#schedule(delayMs) {
if (this.#closed) return;
this.#timer = this.#setTimeout(() => {
this.#timer = null;
void this.#run();
}, delayMs);
this.#timer?.unref?.();
}
async #run() {
if (this.#closed || this.#running) return;
const operation = this.#reconcile();
this.#running = operation;
try {
await operation;
} finally {
if (this.#running === operation) this.#running = null;
}
}
async #reconcile() {
try {
await this.#harness.ensureRunning();
if (this.#closed) return;
const status = await this.#controller.initialize();
if (this.#closed) return;
this.#resolveReady?.(status);
this.#resolveReady = null;
const { configured, connected } = status.totals;
if (connected < configured) {
const delayMs = this.#retryDelays[Math.min(this.#retryIndex, this.#retryDelays.length - 1)];
this.#retryIndex += 1;
this.#logger.warn?.(
`[dsh-weixin] ${connected}/${configured} accounts connected; retrying in ${delayMs}ms`,
);
this.#schedule(delayMs);
return;
}
this.#retryIndex = 0;
this.#schedule(this.#healthyIntervalMs);
} catch (error) {
if (this.#closed) return;
const delayMs = this.#retryDelays[Math.min(this.#retryIndex, this.#retryDelays.length - 1)];
this.#retryIndex += 1;
this.#logger.warn?.(`[dsh-weixin] connection reconciliation failed; retrying in ${delayMs}ms`, error);
this.#schedule(delayMs);
}
}
}
export function createConnectionSupervisor(options) {
return new ConnectionSupervisor(options);
}

View file

@ -0,0 +1,32 @@
import { createProductionController } from './production.mjs';
import { installWeixinRpc } from './rpc.mjs';
export const name = 'dsh-weixin-host';
export const inject = ['connection', 'credentials', 'webServer'];
export async function apply(ctx, config = {}) {
if (config?.controller) return installWeixinRpc(ctx, config.controller, config.rpcOptions);
const production = await createProductionController(ctx, config, config.internals);
const disposeRpc = installWeixinRpc(ctx, production.controller, config.rpcOptions);
ctx.effect(() => async () => {
await production.close();
}, 'dsh-weixin: close account connections');
return disposeRpc;
}
export function createWeixinHostPlugin(config) {
return Object.freeze({ name, inject, apply: (ctx) => apply(ctx, config) });
}
export { createConnectionSupervisor, ConnectionSupervisor } from './connection-supervisor.mjs';
export { createProductionController } from './production.mjs';
export {
WEIXIN_ENDPOINTS,
WEIXIN_RPC_CHANNEL,
WEIXIN_RPC_ENDPOINTS,
createWeixinRpcHandler,
installWeixinRpc,
} from './rpc.mjs';
export { WeixinController } from '../../../../src/channels/weixin/weixin-controller.mjs';
export { WeixinRuntime } from '../../../../src/channels/weixin/weixin-runtime.mjs';

View file

@ -0,0 +1,119 @@
import { unlink } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join, resolve } from 'node:path';
import { WeixinConfigStore } from '../../../../src/channels/weixin/config-store.mjs';
import { HarnessClient } from '../../../../src/channels/weixin/harness-client.mjs';
import { WeixinStateStore } from '../../../../src/channels/weixin/state-store.mjs';
import { createWeixinApi } from '../../../../src/channels/weixin/weixin-api.mjs';
import { WeixinController } from '../../../../src/channels/weixin/weixin-controller.mjs';
import { WeixinRuntime } from '../../../../src/channels/weixin/weixin-runtime.mjs';
import { createConnectionSupervisor } from './connection-supervisor.mjs';
function harnessOrigin(webServer, configured) {
if (configured !== undefined) return new URL(configured);
const port = webServer?.port;
if (!Number.isInteger(port) || port < 1 || port > 65_535) {
throw new Error('dsh-weixin requires an initialized DSH webServer port');
}
return new URL(`http://127.0.0.1:${port}`);
}
function pluginPaths(config) {
const dshHome = resolve(config.dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh'));
const root = resolve(config.dataDir ?? join(dshHome, 'integrations', 'dsh-weixin'));
return {
root,
config: resolve(config.configPath ?? join(root, 'config.json')),
accounts: resolve(config.accountsDir ?? join(root, 'accounts')),
};
}
export async function createProductionController(ctx, config = {}, internals = {}) {
if (!ctx?.credentials) throw new TypeError('dsh-weixin requires ctx.credentials');
if (!ctx?.webServer) throw new TypeError('dsh-weixin requires ctx.webServer');
const ConfigStore = internals.ConfigStore ?? WeixinConfigStore;
const StateStore = internals.StateStore ?? WeixinStateStore;
const Harness = internals.HarnessClient ?? HarnessClient;
const Controller = internals.Controller ?? WeixinController;
const Runtime = internals.Runtime ?? WeixinRuntime;
const api = internals.api ?? createWeixinApi();
const createSupervisor = internals.createConnectionSupervisor ?? createConnectionSupervisor;
const logger = typeof ctx.logger === 'function'
? ctx.logger('dsh-weixin')
: (ctx.logger ?? console);
const paths = pluginPaths(config);
const configStore = await new ConfigStore(paths.config).load();
const stateStores = new Map();
const statePath = (botId) => resolve(paths.accounts, botId, 'state.json');
const stateFor = async (botId) => {
let state = stateStores.get(botId);
if (!state) {
state = await new StateStore(statePath(botId)).load();
stateStores.set(botId, state);
}
return state;
};
const harness = new Harness({
baseUrl: harnessOrigin(ctx.webServer, config.harnessBaseUrl),
workspace: resolve(config.workspace ?? process.cwd()),
agentPreset: config.agentPreset ?? 'standard',
autostart: false,
dshBin: config.dshBin ?? 'dsh',
});
const controller = new Controller({
api,
credentials: ctx.credentials,
configStore,
logger,
createRuntime: async ({ botId, config: accountConfig, token }) => {
const state = await stateFor(botId);
return new Runtime({
api,
config: accountConfig,
token,
harness,
state,
replyTimeoutMs: config.replyTimeoutMs ?? 600_000,
maxMessageChars: config.maxMessageChars ?? 4_000,
logger: {
error: (...args) => logger.error?.(`[${botId}]`, ...args),
warn: (...args) => logger.warn?.(`[${botId}]`, ...args),
info: (...args) => logger.info?.(`[${botId}]`, ...args),
debug: (...args) => logger.debug?.(`[${botId}]`, ...args),
},
});
},
deleteState: async ({ botId }) => {
const state = stateStores.get(botId);
stateStores.delete(botId);
if (state && typeof state.remove === 'function') {
await state.remove();
return;
}
try {
await unlink(statePath(botId));
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
}
},
});
const supervisor = createSupervisor({
controller,
harness,
logger,
retryDelaysMs: config.retryDelaysMs,
healthyIntervalMs: config.healthyIntervalMs,
}).start();
return {
controller,
ready: supervisor.ready,
async close() {
await supervisor.close();
await controller.close();
harness.stopManagedProcess();
},
};
}

View file

@ -0,0 +1,177 @@
import QRCode from 'qrcode';
export const WEIXIN_RPC_CHANNEL = '/weixin';
export const WEIXIN_ENDPOINTS = Object.freeze({
status: 'connection.status',
beginProvisioning: 'provision.begin',
pollProvisioning: 'provision.poll',
submitVerification: 'provision.verify',
cancelProvisioning: 'provision.cancel',
reconnectBot: 'bot.reconnect',
deleteBot: 'bot.delete',
});
export const WEIXIN_RPC_ENDPOINTS = Object.freeze(Object.values(WEIXIN_ENDPOINTS));
function isRecord(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function exactKeys(value, allowed) {
return isRecord(value) && Object.keys(value).every((key) => allowed.includes(key));
}
function validId(value) {
return typeof value === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(value);
}
function payloadFailure(endpoint, payload) {
if (!isRecord(payload)) return 'Payload must be an object.';
if (endpoint === WEIXIN_ENDPOINTS.status) {
return exactKeys(payload, []) ? null : 'connection.status does not accept fields.';
}
if (endpoint === WEIXIN_ENDPOINTS.beginProvisioning) {
return exactKeys(payload, ['locale']) && (payload.locale === undefined || payload.locale === 'zh-CN')
? null
: 'provision.begin received unsupported fields.';
}
if ([WEIXIN_ENDPOINTS.pollProvisioning, WEIXIN_ENDPOINTS.cancelProvisioning].includes(endpoint)) {
return exactKeys(payload, ['attemptId']) && validId(payload.attemptId)
? null
: `${endpoint} requires an attemptId.`;
}
if (endpoint === WEIXIN_ENDPOINTS.submitVerification) {
return exactKeys(payload, ['attemptId', 'verifyCode'])
&& validId(payload.attemptId)
&& typeof payload.verifyCode === 'string'
&& /^\d{4,8}$/.test(payload.verifyCode)
? null
: 'provision.verify requires an attemptId and a 4-to-8-digit code.';
}
if (endpoint === WEIXIN_ENDPOINTS.reconnectBot) {
return exactKeys(payload, ['botId']) && validId(payload.botId)
? null
: 'bot.reconnect requires a botId.';
}
if (endpoint === WEIXIN_ENDPOINTS.deleteBot) {
return exactKeys(payload, ['botId', 'confirm']) && validId(payload.botId) && payload.confirm === true
? null
: 'bot.delete requires a botId and confirm=true.';
}
return 'Unknown Weixin endpoint.';
}
function badRequest(message) {
return { ok: false, error: { code: 'bad-request', message } };
}
function cancelled() {
return { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } };
}
function internalFailure() {
return {
ok: false,
error: { code: 'weixin-operation-failed', message: '微信操作失败,请稍后重试。' },
};
}
async function qrDataUrl(value) {
return QRCode.toDataURL(value, {
type: 'image/png',
errorCorrectionLevel: 'M',
margin: 2,
width: 320,
});
}
async function withEncodedQr(value, encodeQr) {
if (!value || !value.verificationUrl) return value;
return {
...value,
qrCodeDataUrl: await encodeQr(value.verificationUrl),
};
}
async function publicStatus(status, encodeQr) {
const safe = structuredClone(status);
if (safe.provisioning) safe.provisioning = await withEncodedQr(safe.provisioning, encodeQr);
return safe;
}
function assertController(controller) {
if (!controller
|| typeof controller.status !== 'function'
|| typeof controller.startProvisioning !== 'function'
|| typeof controller.registrationStatus !== 'function'
|| typeof controller.submitVerification !== 'function'
|| typeof controller.cancelProvisioning !== 'function'
|| typeof controller.reconnectBot !== 'function'
|| typeof controller.deleteBot !== 'function') {
throw new TypeError('A complete Weixin controller is required');
}
}
export function createWeixinRpcHandler(controller, { encodeQr = qrDataUrl } = {}) {
assertController(controller);
const qrCache = new Map();
const cachedEncode = (url) => {
let encoded = qrCache.get(url);
if (!encoded) {
if (qrCache.size >= 16) qrCache.delete(qrCache.keys().next().value);
encoded = Promise.resolve().then(() => encodeQr(url));
qrCache.set(url, encoded);
}
return encoded;
};
return async (endpoint, payload, signal) => {
if (signal?.aborted) return cancelled();
if (!WEIXIN_RPC_ENDPOINTS.includes(endpoint)) return badRequest('Unknown Weixin endpoint.');
const invalid = payloadFailure(endpoint, payload);
if (invalid) return badRequest(invalid);
try {
let value;
if (endpoint === WEIXIN_ENDPOINTS.status) {
value = await publicStatus(await controller.status(), cachedEncode);
} else if (endpoint === WEIXIN_ENDPOINTS.beginProvisioning) {
const started = await controller.startProvisioning();
if (signal?.aborted) {
await controller.cancelProvisioning(started.attemptId);
return cancelled();
}
value = await withEncodedQr(started, cachedEncode);
} else if (endpoint === WEIXIN_ENDPOINTS.pollProvisioning) {
const current = await controller.registrationStatus(payload.attemptId);
if (!current) return badRequest('The provisioning attempt no longer exists.');
value = await withEncodedQr(current, cachedEncode);
} else if (endpoint === WEIXIN_ENDPOINTS.submitVerification) {
value = await withEncodedQr(
await controller.submitVerification(payload.attemptId, payload.verifyCode),
cachedEncode,
);
} else if (endpoint === WEIXIN_ENDPOINTS.cancelProvisioning) {
value = await controller.cancelProvisioning(payload.attemptId);
if (!value) return badRequest('The provisioning attempt no longer exists.');
} else if (endpoint === WEIXIN_ENDPOINTS.reconnectBot) {
value = await publicStatus(await controller.reconnectBot(payload.botId), cachedEncode);
} else {
value = await publicStatus(await controller.deleteBot(payload.botId), cachedEncode);
}
return signal?.aborted ? cancelled() : { ok: true, value };
} catch {
return signal?.aborted ? cancelled() : internalFailure();
}
};
}
export function installWeixinRpc(ctx, controller, options) {
if (!ctx?.connection?.rpc || typeof ctx.connection.rpc.handle !== 'function') {
throw new TypeError('DSH Host Connection RPC is required');
}
return ctx.connection.rpc.handle(
WEIXIN_RPC_CHANNEL,
createWeixinRpcHandler(controller, options),
{ authority: 'loopback' },
);
}

View file

@ -1,6 +1,6 @@
import { apply as applyDingtalk } from '@xmanrui/dsh-dingtalk';
import { apply as applyFeishu } from '@xmanrui/dsh-feishu';
import { apply as applyWeixin } from '@xmanrui/dsh-weixin';
import { apply as applyDingtalk } from './channels/dingtalk/index.mjs';
import { apply as applyFeishu } from './channels/feishu/index.mjs';
import { apply as applyWeixin } from './channels/weixin/index.mjs';
export const name = 'dsh-im-host';
export const inject = ['connection', 'credentials', 'webServer'];