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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1,204 @@
import { createHash } from 'node:crypto';
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
export const LEGACY_FEISHU_SECRET_REF = 'DSH_FEISHU_APP_SECRET';
function cleanString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function safeId(value) {
const id = cleanString(value);
return id && /^[A-Za-z0-9_-]{1,128}$/.test(id) ? id : null;
}
function legacyBotId(appId) {
return `bot_${createHash('sha256').update(appId).digest('hex').slice(0, 24)}`;
}
function normalizeOwners(value) {
const candidates = Array.isArray(value.ownerOpenIds)
? value.ownerOpenIds
: [value.ownerOpenId];
return [...new Set(candidates.map(cleanString).filter(Boolean))];
}
function normalizeBot(value, { legacy = false } = {}) {
if (!value || typeof value !== 'object') return null;
const appId = cleanString(value.appId);
const ownerOpenIds = normalizeOwners(value);
if (!appId || ownerOpenIds.length === 0) return null;
const id = safeId(value.id) ?? (legacy ? legacyBotId(appId) : null);
const secretRef = cleanString(value.secretRef) ?? (legacy ? LEGACY_FEISHU_SECRET_REF : null);
if (!id || !secretRef) return null;
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(secretRef)) return null;
const domain = value.domain === 'lark' ? 'lark' : 'feishu';
return Object.freeze({
id,
appId,
secretRef,
ownerOpenIds: Object.freeze(ownerOpenIds),
domain,
botName: cleanString(value.botName),
botOpenId: cleanString(value.botOpenId),
activated: value.activated ?? null,
deletionPending: value.deletionPending === true,
connectedAt: cleanString(value.connectedAt),
createdAt: cleanString(value.createdAt) ?? cleanString(value.connectedAt),
});
}
function normalizeDocument(value) {
if (!value || typeof value !== 'object') return null;
if (value.version === 2 && Array.isArray(value.bots)) {
const bots = value.bots.map((bot) => normalizeBot(bot));
if (bots.some((bot) => bot === null)) {
throw new Error('dsh-feishu config contains an invalid bot entry');
}
const ids = new Set();
const refs = new Set();
const appIds = new Set();
for (const bot of bots) {
if (ids.has(bot.id) || refs.has(bot.secretRef) || appIds.has(bot.appId)) {
throw new Error('dsh-feishu config contains duplicate bot identities');
}
ids.add(bot.id);
refs.add(bot.secretRef);
appIds.add(bot.appId);
}
return { value: Object.freeze({ version: 2, bots: Object.freeze(bots) }), migrated: false };
}
// Version 1 was a single non-secret bot object. Preserve its existing
// credential reference so an environment-backed secret remains usable.
const legacyBot = normalizeBot(value, { legacy: true });
if (!legacyBot) return null;
return {
value: Object.freeze({ version: 2, bots: Object.freeze([legacyBot]) }),
migrated: true,
};
}
/** Stores only non-secret onboarding facts for all Feishu bots. */
export class PluginConfigStore {
#path;
#value = Object.freeze({ version: 2, bots: Object.freeze([]) });
#writeQueue = Promise.resolve();
constructor(path) {
this.#path = path;
}
async load() {
try {
const parsed = JSON.parse(await readFile(this.#path, 'utf8'));
const normalized = normalizeDocument(parsed);
if (!normalized) throw new Error('dsh-feishu config is incomplete or invalid');
this.#value = normalized.value;
if (normalized.migrated) await this.#writeDocument(this.#value);
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
this.#value = Object.freeze({ version: 2, bots: Object.freeze([]) });
}
return this;
}
/** Backward-compatible single-bot view used by the original controller. */
get() {
const bot = this.#value.bots[0];
if (!bot) return null;
const result = structuredClone(bot);
result.ownerOpenId = result.ownerOpenIds[0];
return result;
}
list() {
return structuredClone(this.#value.bots);
}
getBot(id) {
const bot = this.#value.bots.find((candidate) => candidate.id === id);
return bot ? structuredClone(bot) : null;
}
/** Backward-compatible save replaces the original single-bot view. */
async save(value) {
const fallback = { ...value };
if (!fallback.id) fallback.id = legacyBotId(cleanString(fallback.appId) ?? 'invalid');
if (!fallback.secretRef) fallback.secretRef = LEGACY_FEISHU_SECRET_REF;
const normalized = normalizeBot(fallback);
if (!normalized) throw new Error('Refusing to persist incomplete dsh-feishu configuration');
await this.#replaceBots([normalized]);
return this.get();
}
async saveBot(value) {
const normalized = normalizeBot(value);
if (!normalized) throw new Error('Refusing to persist incomplete dsh-feishu bot configuration');
return this.#mutate((bots) => {
const collision = bots.find((bot) => bot.secretRef === normalized.secretRef && bot.id !== normalized.id);
if (collision) throw new Error('Refusing to share a credential reference between Feishu bots');
const appCollision = bots.find((bot) => bot.appId === normalized.appId && bot.id !== normalized.id);
if (appCollision) throw new Error('Refusing to persist the same Feishu app twice');
const index = bots.findIndex((bot) => bot.id === normalized.id);
if (index === -1) bots.push(normalized);
else bots[index] = normalized;
return structuredClone(normalized);
});
}
async removeBot(id) {
if (!safeId(id)) throw new TypeError('Invalid Feishu bot id');
return this.#mutate((bots) => {
const index = bots.findIndex((bot) => bot.id === id);
if (index === -1) return null;
const [removed] = bots.splice(index, 1);
return structuredClone(removed);
});
}
async clear() {
const operation = this.#writeQueue.then(async () => {
try {
await unlink(this.#path);
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
}
this.#value = Object.freeze({ version: 2, bots: Object.freeze([]) });
});
this.#writeQueue = operation.then(() => undefined, () => undefined);
await operation;
}
async #replaceBots(bots) {
const document = Object.freeze({ version: 2, bots: Object.freeze([...bots]) });
const operation = this.#writeQueue.then(async () => {
await this.#writeDocument(document);
this.#value = document;
});
this.#writeQueue = operation.then(() => undefined, () => undefined);
await operation;
}
async #mutate(mutator) {
let result;
const operation = this.#writeQueue.then(async () => {
const bots = [...this.#value.bots];
result = mutator(bots);
const document = Object.freeze({ version: 2, bots: Object.freeze(bots) });
await this.#writeDocument(document);
this.#value = document;
});
this.#writeQueue = operation.then(() => undefined, () => undefined);
await operation;
return result;
}
async #writeDocument(document) {
await mkdir(dirname(this.#path), { recursive: true, mode: 0o700 });
const temporary = `${this.#path}.tmp`;
await writeFile(temporary, `${JSON.stringify(document, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
await rename(temporary, this.#path);
}
}

View file

@ -0,0 +1,248 @@
import { RegistrationManager } from './registration-manager.mjs';
export const FEISHU_SECRET_REF = 'DSH_FEISHU_APP_SECRET';
export const REQUIRED_TENANT_SCOPES = Object.freeze([
'im:message.p2p_msg:readonly',
'im:message.group_at_msg:readonly',
'im:message:send_as_bot',
'im:message.reactions:write_only',
'im:message:recall',
'cardkit:card:write',
]);
function safeConnectionStatus(runtime) {
if (!runtime) return {
ready: false,
feishuLongConnectionState: 'idle',
harnessReachable: false,
};
return runtime.status;
}
function publicBot(config) {
if (!config) return null;
const appIdMasked = config.appId.length > 12
? `${config.appId.slice(0, 8)}••••${config.appId.slice(-4)}`
: 'cli_••••';
return {
name: config.botName,
appIdMasked,
openId: config.botOpenId,
activated: config.activated,
domain: config.domain,
};
}
/** Coordinates QR provisioning, durable credentials and the live chat runtime. */
export class DshFeishuController {
#registerApp;
#verifyApp;
#credentials;
#configStore;
#createRuntime;
#registration;
#runtime = null;
#lastError = null;
#transition = Promise.resolve();
constructor({ registerApp, verifyApp, credentials, configStore, createRuntime }) {
if (typeof registerApp !== 'function') throw new Error('registerApp is required');
if (typeof verifyApp !== 'function') throw new Error('verifyApp is required');
if (!credentials) throw new Error('credentials service is required');
if (!configStore) throw new Error('config store is required');
if (typeof createRuntime !== 'function') throw new Error('createRuntime is required');
this.#registerApp = registerApp;
this.#verifyApp = verifyApp;
this.#credentials = credentials;
this.#configStore = configStore;
this.#createRuntime = createRuntime;
this.#registration = new RegistrationManager({
registerApp: this.#registerApp,
onCredentials: (result) => this.#serialize(() => this.#acceptCredentials(result)),
});
}
async initialize() {
const config = this.#configStore.get();
if (!config) return this.status();
return this.#serialize(async () => {
const resolved = await this.#credentials.resolve(FEISHU_SECRET_REF);
if (!resolved?.value) {
this.#lastError = {
code: 'missing_credentials',
message: '机器人凭据缺失,请重新扫码接入。',
};
return this.status();
}
try {
await this.#startRuntime(config, resolved.value);
this.#lastError = null;
} catch {
this.#lastError = {
code: 'connection_failed',
message: '机器人暂时无法连接飞书,请重试。',
};
}
return this.status();
});
}
startRegistration() {
this.#lastError = null;
this.#registration.start({
source: 'deepseek-harness',
createOnly: true,
appPreset: {
name: '{user} 的北汇星河 AI 助手',
desc: '连接飞书与 DeepSeek Harness,在聊天中使用企业 AI 助手。',
},
addons: {
preset: false,
scopes: { tenant: [...REQUIRED_TENANT_SCOPES] },
events: { items: { tenant: ['im.message.receive_v1'] } },
},
});
return this.status();
}
cancelRegistration() {
this.#registration.cancel();
return this.status();
}
async reconnect() {
return this.#serialize(async () => {
const config = this.#configStore.get();
const resolved = await this.#credentials.resolve(FEISHU_SECRET_REF);
if (!config || !resolved?.value) {
this.#lastError = {
code: 'missing_credentials',
message: '没有可用的机器人凭据,请重新扫码接入。',
};
return this.status();
}
try {
await this.#startRuntime(config, resolved.value);
this.#lastError = null;
} catch {
this.#lastError = {
code: 'connection_failed',
message: '机器人暂时无法连接飞书,请重试。',
};
}
return this.status();
});
}
async disconnect() {
this.#registration.cancel();
return this.#serialize(async () => {
await this.#stopRuntime();
await this.#configStore.clear();
try {
await this.#credentials.unset(FEISHU_SECRET_REF);
} catch {
// A read-only environment value may shadow the managed store. Clearing
// the non-secret config still prevents automatic reuse of that value.
}
this.#lastError = null;
return this.status();
});
}
async close() {
this.#registration.cancel();
await this.#serialize(() => this.#stopRuntime());
}
status() {
const config = this.#configStore.get();
const registration = this.#registration.status();
const connection = safeConnectionStatus(this.#runtime);
const connected = connection.ready === true
&& connection.feishuLongConnectionState === 'connected'
&& connection.harnessReachable === true;
let phase = 'unconfigured';
if (connected) phase = 'connected';
else if (['starting', 'qr_ready', 'polling', 'slow_down', 'domain_switched'].includes(registration.state)) {
phase = 'registering';
} else if (registration.state === 'saving') phase = 'connecting';
else if (this.#lastError || registration.state === 'error') phase = 'error';
else if (config) phase = 'disconnected';
return {
phase,
connected,
configured: Boolean(config),
bot: publicBot(config),
registration,
connection,
error: this.#lastError ?? registration.error ?? null,
};
}
async #acceptCredentials(result) {
const appId = result.client_id;
const appSecret = result.client_secret;
const ownerOpenId = result.user_info?.open_id;
const domain = result.user_info?.tenant_brand === 'lark' ? 'lark' : 'feishu';
if (!ownerOpenId) throw new Error('Feishu registration returned no owner open_id');
const bot = await this.#verifyApp({ appId, appSecret, domain });
await this.#credentials.set(FEISHU_SECRET_REF, appSecret);
let config;
try {
config = await this.#configStore.save({
appId,
ownerOpenId,
domain,
botName: bot.name,
botOpenId: bot.openId,
activated: bot.activated,
connectedAt: new Date().toISOString(),
});
} catch (error) {
await this.#credentials.unset(FEISHU_SECRET_REF).catch(() => undefined);
throw error;
}
try {
await this.#startRuntime(config, appSecret);
this.#lastError = null;
} catch (error) {
this.#lastError = {
code: 'connection_failed',
message: '机器人已经创建,但长连接未就绪,请点击重试。',
};
throw error;
}
}
async #startRuntime(config, appSecret) {
await this.#stopRuntime();
const runtime = await this.#createRuntime({ config, appSecret });
this.#runtime = runtime;
try {
await runtime.start();
} catch (error) {
if (this.#runtime === runtime) this.#runtime = null;
await runtime.stop({ preserveError: true }).catch(() => undefined);
throw error;
}
}
async #stopRuntime() {
const runtime = this.#runtime;
this.#runtime = null;
if (runtime) await runtime.stop();
}
#serialize(operation) {
const result = this.#transition.then(operation, operation);
this.#transition = result.then(() => undefined, () => undefined);
return result;
}
}

View file

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

View file

@ -0,0 +1,71 @@
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
const EMPTY_STATE = Object.freeze({ version: 1, sessions: {}, seenMessageIds: [] });
export class StateStore {
#path;
#state = structuredClone(EMPTY_STATE);
#writeQueue = Promise.resolve();
constructor(path) {
this.#path = path;
}
async load() {
try {
const parsed = JSON.parse(await readFile(this.#path, 'utf8'));
this.#state = {
version: 1,
sessions: parsed.sessions && typeof parsed.sessions === 'object' ? parsed.sessions : {},
seenMessageIds: Array.isArray(parsed.seenMessageIds) ? parsed.seenMessageIds.slice(-1000) : [],
};
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
await this.#persist();
}
return this;
}
sessionFor(key) {
return this.#state.sessions[key] ?? null;
}
async setSession(key, sessionId) {
this.#state.sessions[key] = sessionId;
await this.#persist();
}
async clearSession(key) {
delete this.#state.sessions[key];
await this.#persist();
}
hasSeen(messageId) {
return this.#state.seenMessageIds.includes(messageId);
}
async markSeen(messageId) {
if (this.hasSeen(messageId)) return;
this.#state.seenMessageIds.push(messageId);
if (this.#state.seenMessageIds.length > 1000) {
this.#state.seenMessageIds.splice(0, this.#state.seenMessageIds.length - 1000);
}
await this.#persist();
}
snapshot() {
return structuredClone(this.#state);
}
async #persist() {
const snapshot = JSON.stringify(this.#state, null, 2) + '\n';
this.#writeQueue = this.#writeQueue.then(async () => {
await mkdir(dirname(this.#path), { recursive: true, mode: 0o700 });
const temporary = `${this.#path}.tmp`;
await writeFile(temporary, snapshot, { encoding: 'utf8', mode: 0o600 });
await rename(temporary, this.#path);
});
await this.#writeQueue;
}
}