Add Telegram and Discord IM channels

This commit is contained in:
xmanrui 2026-08-16 14:47:16 +08:00
parent 7123fce47a
commit cb74e1c4c7
66 changed files with 8579 additions and 1910 deletions

View file

@ -0,0 +1,24 @@
import {
deriveTokenBotIdentity,
maskPlatformId,
TokenBotConfigStore,
} from '../shared/token-config-store.mjs';
const IDENTITY_OPTIONS = Object.freeze({
botPrefix: 'discord',
tokenRefPrefix: 'DSH_DISCORD_BOT_TOKEN',
});
export function deriveDiscordBotIdentity(platformId) {
return deriveTokenBotIdentity(platformId, IDENTITY_OPTIONS);
}
export function maskDiscordBotId(platformId) {
return maskPlatformId(platformId, 'Discord机器人');
}
export class DiscordConfigStore extends TokenBotConfigStore {
constructor(path) {
super(path, { channel: 'Discord', ...IDENTITY_OPTIONS });
}
}

View file

@ -0,0 +1,153 @@
const DEFAULT_BASE_URL = 'https://discord.com/api/v10/';
function cleanString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function requestSignal(signal, timeoutMs) {
const timeout = AbortSignal.timeout(timeoutMs);
return signal ? AbortSignal.any([signal, timeout]) : timeout;
}
function delay(ms, signal) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
return;
}
const timer = setTimeout(resolve, ms);
timer?.unref?.();
signal?.addEventListener('abort', () => {
clearTimeout(timer);
reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
}, { once: true });
});
}
function snowflake(value, name) {
const id = cleanString(value);
if (!id || !/^\d{5,30}$/.test(id)) throw new TypeError(`Invalid Discord ${name}`);
return id;
}
export function validDiscordToken(value) {
return typeof value === 'string'
&& /^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{20,}$/.test(value.trim());
}
export class DiscordApi {
#token;
#fetch;
#baseUrl;
constructor({ token, fetchImpl = fetch, baseUrl = DEFAULT_BASE_URL }) {
if (!validDiscordToken(token)) throw new TypeError('Discord Bot Token is invalid');
if (typeof fetchImpl !== 'function') throw new TypeError('DiscordApi requires fetch');
this.#token = token.trim();
this.#fetch = fetchImpl;
this.#baseUrl = new URL(baseUrl);
}
getCurrentUser(options = {}) {
return this.#request('users/@me', { ...options, method: 'GET' });
}
getGatewayBot(options = {}) {
return this.#request('gateway/bot', { ...options, method: 'GET' });
}
createMessage({ channelId, content, replyToMessageId, signal }) {
return this.#request(`channels/${snowflake(channelId, 'channel id')}/messages`, {
method: 'POST',
signal,
body: {
content,
allowed_mentions: { parse: [], replied_user: false },
...(replyToMessageId ? {
message_reference: {
message_id: snowflake(replyToMessageId, 'message id'),
channel_id: snowflake(channelId, 'channel id'),
fail_if_not_exists: false,
},
} : {}),
},
});
}
editMessage({ channelId, messageId, content, signal }) {
return this.#request(
`channels/${snowflake(channelId, 'channel id')}/messages/${snowflake(messageId, 'message id')}`,
{
method: 'PATCH',
signal,
body: { content, allowed_mentions: { parse: [], replied_user: false } },
},
);
}
sendTyping({ channelId, signal }) {
return this.#request(`channels/${snowflake(channelId, 'channel id')}/typing`, {
method: 'POST',
signal,
expectBody: false,
});
}
async #request(path, {
method,
body,
signal,
timeoutMs = 15_000,
expectBody = true,
retry = true,
}) {
let response;
try {
response = await this.#fetch(new URL(path, this.#baseUrl), {
method,
headers: {
authorization: `Bot ${this.#token}`,
'content-type': 'application/json',
'user-agent': 'DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 0.1.0)',
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
signal: requestSignal(signal, timeoutMs),
redirect: 'error',
});
} catch (error) {
if (error?.name === 'AbortError' || error?.name === 'TimeoutError') throw error;
throw new Error(`Discord ${method} transport failed`);
}
let parsed = null;
if (expectBody || response.status === 429 || !response.ok) {
try {
parsed = await response.json();
} catch {
if (expectBody) throw new Error(`Discord ${method} returned invalid JSON`);
}
}
if (response.status === 429 && retry) {
const retryAfterMs = Math.min(10_000, Math.max(50, Number(parsed?.retry_after) * 1_000 || 1_000));
await delay(retryAfterMs, signal);
return this.#request(path, { method, body, signal, timeoutMs, expectBody, retry: false });
}
if (!response.ok) {
const error = new Error(cleanString(parsed?.message) ?? `Discord API failed with HTTP ${response.status}`);
error.code = `discord-${response.status}`;
throw error;
}
return expectBody ? parsed : null;
}
}
export async function inspectDiscordToken(token, options = {}) {
const api = new DiscordApi({ token, ...options });
const bot = await api.getCurrentUser();
if (!bot?.id || bot?.bot !== true) throw new Error('Discord token does not belong to a bot');
return {
platformId: String(bot.id),
name: cleanString(bot.global_name) ?? cleanString(bot.username) ?? 'Discord机器人',
username: cleanString(bot.username),
};
}

View file

@ -0,0 +1,15 @@
import { TextHarnessBridge, createTextBridgeStatus } from '../shared/text-harness-bridge.mjs';
export const DISCORD_DESCRIPTOR = Object.freeze({
key: 'discord',
label: 'Discord',
connectionLabel: ' Gateway 长连接',
});
export class DiscordHarnessBridge extends TextHarnessBridge {
constructor(options) {
super({ descriptor: DISCORD_DESCRIPTOR, ...options });
}
}
export { createTextBridgeStatus as createDiscordBridgeStatus };

View file

@ -0,0 +1,16 @@
import { TokenBotController } from '../shared/token-bot-controller.mjs';
import { deriveDiscordBotIdentity, maskDiscordBotId } from './config-store.mjs';
import { inspectDiscordToken } from './discord-api.mjs';
import { DISCORD_DESCRIPTOR } from './discord-bridge.mjs';
export class DiscordController extends TokenBotController {
constructor(options) {
super({
...options,
descriptor: DISCORD_DESCRIPTOR,
inspectToken: options.inspectToken ?? inspectDiscordToken,
deriveIdentity: deriveDiscordBotIdentity,
maskPlatformId: maskDiscordBotId,
});
}
}

View file

@ -0,0 +1,460 @@
import { createEditableMessageStream, splitMessageText } from '../shared/editable-message-stream.mjs';
import { DiscordApi } from './discord-api.mjs';
import { createDiscordBridgeStatus, DiscordHarnessBridge } from './discord-bridge.mjs';
const DISCORD_GATEWAY_INTENTS = (1 << 0) | (1 << 9) | (1 << 12);
const RECONNECT_DELAYS_MS = Object.freeze([1_000, 3_000, 5_000, 10_000, 30_000]);
function socketUrl(value) {
const url = new URL(value);
if (url.protocol !== 'wss:') throw new Error('Discord returned an insecure Gateway URL');
url.searchParams.set('v', '10');
url.searchParams.set('encoding', 'json');
return url.href;
}
function addSocketListener(socket, event, listener) {
if (typeof socket.addEventListener === 'function') socket.addEventListener(event, listener);
else if (typeof socket.on === 'function') socket.on(event, listener);
else throw new TypeError('Discord WebSocket does not support events');
}
function eventData(event) {
if (typeof event === 'string') return event;
if (typeof event?.data === 'string') return event.data;
if (Buffer.isBuffer(event)) return event.toString('utf8');
if (Buffer.isBuffer(event?.data)) return event.data.toString('utf8');
return null;
}
function gatewayCloseError(code) {
if (code === 4004) {
const error = new Error('Discord Bot Token 无效,请重新填写。');
error.code = 'discord-401';
return error;
}
if (code === 4013 || code === 4014) {
const error = new Error('Discord Gateway Intents 配置不正确,请检查 Developer Portal 的 Bot 设置。');
error.code = 'discord-intents';
return error;
}
const error = new Error(`Discord Gateway closed (${code || 'unknown'})`);
error.code = 'discord-gateway-closed';
return error;
}
function stripBotMention(text, botId) {
if (typeof text !== 'string') return '';
return text.replace(new RegExp(`<@!?${botId}>`, 'g'), '').trim();
}
export function normalizeDiscordMessage(message, botId) {
if (!message?.id || !message?.channel_id || !message?.author?.id) return null;
const direct = !message.guild_id;
const addressed = direct
|| message.mentions?.some((mention) => String(mention?.id) === String(botId));
return {
messageId: String(message.id),
senderId: String(message.author.id),
senderIsBot: message.author.bot === true,
kind: direct ? 'direct' : 'group',
conversationId: String(message.channel_id),
content: stripBotMention(message.content ?? '', botId),
addressed,
replyTarget: {
channelId: String(message.channel_id),
replyToMessageId: String(message.id),
},
};
}
class DiscordBotClient {
#api;
#signal;
constructor({ api, signal }) {
this.#api = api;
this.#signal = signal;
}
async sendText(target, text) {
const chunks = splitMessageText(text, 1_900);
let result = null;
for (const [index, chunk] of chunks.entries()) {
result = await this.#api.createMessage({
channelId: target.channelId,
content: chunk,
replyToMessageId: index === 0 ? target.replyToMessageId : undefined,
signal: this.#signal,
});
}
return result;
}
sendTyping(target) {
return this.#api.sendTyping({ channelId: target.channelId, signal: this.#signal });
}
async openStream(target) {
const stream = createEditableMessageStream({
limit: 1_900,
create: async (content) => {
const message = await this.#api.createMessage({
channelId: target.channelId,
content,
replyToMessageId: target.replyToMessageId,
signal: this.#signal,
});
return message.id;
},
edit: (messageId, content) => this.#api.editMessage({
channelId: target.channelId,
messageId,
content,
signal: this.#signal,
}),
sendRemainder: (content) => this.#api.createMessage({
channelId: target.channelId,
content,
signal: this.#signal,
}),
});
return stream.start();
}
}
export function createDiscordRuntimeStatus() {
return {
startedAt: null,
ready: false,
connectionState: 'idle',
harnessReachable: false,
lastCheckedAt: null,
lastConnectedAt: null,
lastError: null,
...createDiscordBridgeStatus(),
};
}
export class DiscordRuntime {
#config;
#token;
#harness;
#state;
#logger;
#replyTimeoutMs;
#connectTimeoutMs;
#createApi;
#createWebSocket;
#random;
#status = createDiscordRuntimeStatus();
#api = null;
#bridge = null;
#abortController = null;
#socket = null;
#gatewayUrl = null;
#resumeUrl = null;
#sessionId = null;
#sequence = null;
#heartbeatTimer = null;
#heartbeatAcked = true;
#reconnectTimer = null;
#reconnectAttempt = 0;
#generation = 0;
#stopped = true;
#starting = null;
constructor({
config,
token,
harness,
state,
logger = console,
replyTimeoutMs = 600_000,
connectTimeoutMs = 20_000,
createApi = (options) => new DiscordApi(options),
createWebSocket = (url) => new WebSocket(url),
random = Math.random,
}) {
if (!config || !token || !harness || !state) {
throw new TypeError('DiscordRuntime requires config, token, Harness, and state');
}
if (typeof createWebSocket !== 'function') throw new TypeError('DiscordRuntime requires WebSocket');
this.#config = config;
this.#token = token;
this.#harness = harness;
this.#state = state;
this.#logger = logger;
this.#replyTimeoutMs = replyTimeoutMs;
this.#connectTimeoutMs = connectTimeoutMs;
this.#createApi = createApi;
this.#createWebSocket = createWebSocket;
this.#random = random;
}
get status() {
return structuredClone(this.#status);
}
async start() {
if (this.#status.ready && this.#socket) return this.status;
if (this.#starting) return this.#starting;
this.#starting = this.#start().finally(() => {
this.#starting = null;
});
return this.#starting;
}
async #start() {
await this.stop();
this.#stopped = false;
this.#sessionId = null;
this.#resumeUrl = null;
this.#sequence = null;
this.#reconnectAttempt = 0;
this.#status.startedAt = new Date().toISOString();
this.#status.connectionState = 'connecting';
this.#status.lastError = null;
await this.#harness.ensureRunning();
this.#status.harnessReachable = true;
const controller = new AbortController();
this.#abortController = controller;
const api = this.#createApi({ token: this.#token });
this.#api = api;
try {
const [bot, gateway] = await Promise.all([
api.getCurrentUser({ signal: controller.signal }),
api.getGatewayBot({ signal: controller.signal }),
]);
if (String(bot?.id ?? '') !== this.#config.platformId || bot?.bot !== true) {
throw new Error('Discord token identity does not match the saved bot');
}
this.#gatewayUrl = gateway?.url;
const client = new DiscordBotClient({ api, signal: controller.signal });
this.#bridge = new DiscordHarnessBridge({
bot: client,
harness: this.#harness,
state: this.#state,
status: this.#status,
logger: this.#logger,
replyTimeoutMs: this.#replyTimeoutMs,
});
let timer;
try {
await Promise.race([
this.#openSocket(false),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error('Discord Gateway did not become ready in time')), this.#connectTimeoutMs);
}),
]);
} finally {
clearTimeout(timer);
}
return this.status;
} catch (error) {
this.#status.ready = false;
this.#status.connectionState = 'failed';
this.#status.lastError = error?.message ?? String(error);
await this.stop();
throw error;
}
}
#openSocket(resume) {
if (this.#stopped) return Promise.reject(new Error('Discord runtime is stopped'));
const generation = ++this.#generation;
const url = socketUrl(resume && this.#resumeUrl ? this.#resumeUrl : this.#gatewayUrl);
const socket = this.#createWebSocket(url);
this.#socket = socket;
let settled = false;
return new Promise((resolve, reject) => {
const markReady = () => {
if (settled || generation !== this.#generation) return;
settled = true;
this.#reconnectAttempt = 0;
const now = Date.now();
this.#status.ready = true;
this.#status.connectionState = 'connected';
this.#status.lastCheckedAt = now;
this.#status.lastConnectedAt = now;
this.#status.lastError = null;
resolve();
};
addSocketListener(socket, 'message', (event) => {
if (generation !== this.#generation || this.#stopped) return;
const raw = eventData(event);
if (!raw) return;
let packet;
try {
packet = JSON.parse(raw);
} catch {
this.#logger.warn?.('[dsh-im:discord] ignored malformed Gateway JSON');
return;
}
if (Number.isSafeInteger(packet.s)) this.#sequence = packet.s;
if (packet.op === 10) {
this.#startHeartbeat(packet.d?.heartbeat_interval, socket, generation);
if (resume && this.#sessionId) {
this.#sendGateway(socket, {
op: 6,
d: { token: this.#token, session_id: this.#sessionId, seq: this.#sequence },
});
} else {
this.#sendGateway(socket, {
op: 2,
d: {
token: this.#token,
intents: DISCORD_GATEWAY_INTENTS,
properties: {
os: process.platform,
browser: 'dsh-im',
device: 'dsh-im',
},
},
});
}
return;
}
if (packet.op === 11) {
this.#heartbeatAcked = true;
this.#status.lastCheckedAt = Date.now();
return;
}
if (packet.op === 1) {
this.#heartbeat(socket);
return;
}
if (packet.op === 7) {
socket.close(4000, 'Reconnect requested');
return;
}
if (packet.op === 9) {
if (packet.d !== true) {
this.#sessionId = null;
this.#resumeUrl = null;
this.#sequence = null;
}
socket.close(4000, 'Invalid session');
return;
}
if (packet.op !== 0) return;
if (packet.t === 'READY') {
this.#sessionId = packet.d?.session_id ?? null;
this.#resumeUrl = packet.d?.resume_gateway_url ?? null;
markReady();
} else if (packet.t === 'RESUMED') {
markReady();
} else if (packet.t === 'MESSAGE_CREATE') {
const message = normalizeDiscordMessage(packet.d, this.#config.platformId);
if (message) void this.#bridge?.accept(message);
}
});
addSocketListener(socket, 'close', (event = {}) => {
if (generation !== this.#generation) return;
this.#clearHeartbeat();
if (this.#socket === socket) this.#socket = null;
if (this.#stopped) {
if (!settled) reject(new DOMException('Stopped', 'AbortError'));
return;
}
const error = gatewayCloseError(Number(event.code) || 0);
this.#status.ready = false;
this.#status.connectionState = 'connecting';
this.#status.lastError = error.message;
if (!settled) {
settled = true;
reject(error);
}
if (error.code === 'discord-401' || error.code === 'discord-intents') {
this.#status.connectionState = 'failed';
return;
}
this.#scheduleReconnect();
});
addSocketListener(socket, 'error', () => {
if (generation !== this.#generation || this.#stopped) return;
this.#status.lastError = 'Discord Gateway WebSocket error';
});
});
}
#sendGateway(socket, payload) {
if (socket.readyState !== 1) return;
socket.send(JSON.stringify(payload));
}
#startHeartbeat(interval, socket, generation) {
this.#clearHeartbeat();
if (!Number.isFinite(interval) || interval < 1_000) {
socket.close(4000, 'Invalid heartbeat interval');
return;
}
this.#heartbeatAcked = true;
const schedule = (delay) => {
this.#heartbeatTimer = setTimeout(() => {
if (this.#stopped || generation !== this.#generation || this.#socket !== socket) return;
if (!this.#heartbeatAcked) {
socket.close(4000, 'Heartbeat was not acknowledged');
return;
}
this.#heartbeat(socket);
schedule(interval);
}, delay);
this.#heartbeatTimer?.unref?.();
};
schedule(Math.floor(interval * this.#random()));
}
#heartbeat(socket) {
this.#heartbeatAcked = false;
this.#sendGateway(socket, { op: 1, d: this.#sequence });
}
#clearHeartbeat() {
if (this.#heartbeatTimer !== null) clearTimeout(this.#heartbeatTimer);
this.#heartbeatTimer = null;
this.#heartbeatAcked = true;
}
#scheduleReconnect() {
if (this.#stopped || this.#reconnectTimer !== null) return;
const delay = RECONNECT_DELAYS_MS[Math.min(this.#reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)];
this.#reconnectAttempt += 1;
this.#reconnectTimer = setTimeout(() => {
this.#reconnectTimer = null;
void this.#openSocket(Boolean(this.#sessionId)).catch((error) => {
if (this.#stopped) return;
this.#logger.warn?.('[dsh-im:discord] Gateway reconnect failed:', error);
this.#scheduleReconnect();
});
}, delay);
this.#reconnectTimer?.unref?.();
}
async stop() {
this.#stopped = true;
this.#generation += 1;
this.#abortController?.abort();
this.#abortController = null;
if (this.#reconnectTimer !== null) clearTimeout(this.#reconnectTimer);
this.#reconnectTimer = null;
this.#clearHeartbeat();
const socket = this.#socket;
const bridge = this.#bridge;
this.#socket = null;
this.#bridge = null;
this.#api = null;
try {
if (socket && socket.readyState < 2) socket.close(1000, 'Plugin stopped');
} catch (error) {
this.#logger.warn?.(`[dsh-im:discord] bot ${this.#config.botId} failed to close Gateway:`, error);
}
await Promise.race([
bridge?.waitForIdle() ?? Promise.resolve(),
new Promise((resolve) => setTimeout(resolve, 2_000)),
]);
this.#status.ready = false;
this.#status.connectionState = 'idle';
return this.status;
}
}

View file

@ -0,0 +1,3 @@
import { HarnessClient } from '../weixin/harness-client.mjs';
export class DiscordHarnessClient extends HarnessClient {}

View file

@ -0,0 +1,3 @@
import { ConversationStateStore } from '../shared/conversation-state-store.mjs';
export class DiscordStateStore extends ConversationStateStore {}

View file

@ -0,0 +1,107 @@
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
const EMPTY_STATE = Object.freeze({ version: 1, sessions: {}, seenMessageIds: [], cursor: null });
function normalizeState(value) {
if (!value || typeof value !== 'object') return structuredClone(EMPTY_STATE);
const sessions = {};
if (value.sessions && typeof value.sessions === 'object' && !Array.isArray(value.sessions)) {
for (const [key, sessionId] of Object.entries(value.sessions)) {
if (typeof key === 'string' && key && typeof sessionId === 'string' && sessionId) {
sessions[key] = sessionId;
}
}
}
return {
version: 1,
sessions,
seenMessageIds: Array.isArray(value.seenMessageIds)
? value.seenMessageIds.filter((id) => typeof id === 'string' && id).slice(-1_000)
: [],
cursor: Number.isSafeInteger(value.cursor) && value.cursor >= 0 ? value.cursor : null,
};
}
export class ConversationStateStore {
#path;
#state = structuredClone(EMPTY_STATE);
#writeQueue = Promise.resolve();
constructor(path) {
this.#path = path;
}
async load() {
try {
this.#state = normalizeState(JSON.parse(await readFile(this.#path, 'utf8')));
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
this.#state = structuredClone(EMPTY_STATE);
await this.#persist();
}
return this;
}
sessionFor(key) {
return this.#state.sessions[key] ?? null;
}
async setSession(key, sessionId) {
this.#state.sessions[key] = sessionId;
await this.#persist();
}
async clearSession(key) {
delete this.#state.sessions[key];
await this.#persist();
}
hasSeen(messageId) {
return this.#state.seenMessageIds.includes(messageId);
}
async markSeen(messageId) {
if (this.hasSeen(messageId)) return;
this.#state.seenMessageIds.push(messageId);
if (this.#state.seenMessageIds.length > 1_000) {
this.#state.seenMessageIds.splice(0, this.#state.seenMessageIds.length - 1_000);
}
await this.#persist();
}
cursor() {
return this.#state.cursor;
}
async setCursor(cursor) {
if (!Number.isSafeInteger(cursor) || cursor < 0) throw new TypeError('Invalid update cursor');
this.#state.cursor = cursor;
await this.#persist();
}
snapshot() {
return structuredClone(this.#state);
}
async remove() {
try {
await unlink(this.#path);
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
}
this.#state = structuredClone(EMPTY_STATE);
}
async #persist() {
const snapshot = `${JSON.stringify(this.#state, null, 2)}\n`;
const operation = this.#writeQueue.then(async () => {
await mkdir(dirname(this.#path), { recursive: true, mode: 0o700 });
const temporary = `${this.#path}.tmp`;
await writeFile(temporary, snapshot, { encoding: 'utf8', mode: 0o600 });
await rename(temporary, this.#path);
});
this.#writeQueue = operation.then(() => undefined, () => undefined);
await operation;
}
}

View file

@ -0,0 +1,81 @@
export function splitMessageText(value, limit) {
const text = typeof value === 'string' ? value.trim() : '';
if (!text) return [];
const chunks = [];
let remaining = text;
while (remaining.length > limit) {
let cut = remaining.lastIndexOf('\n', limit);
if (cut < Math.floor(limit * 0.55)) cut = remaining.lastIndexOf(' ', limit);
if (cut < Math.floor(limit * 0.55)) cut = limit;
chunks.push(remaining.slice(0, cut).trim());
remaining = remaining.slice(cut).trimStart();
}
if (remaining) chunks.push(remaining);
return chunks;
}
export function createEditableMessageStream({
initialText = '正在处理…',
limit,
updateIntervalMs = 800,
create,
edit,
sendRemainder,
logger = console,
}) {
let messageId;
let pending = null;
let timer = null;
let inFlight = null;
let closed = false;
let lastSent = initialText;
const schedule = () => {
if (closed || timer !== null || inFlight || !pending) return;
timer = setTimeout(() => {
timer = null;
const text = pending;
pending = null;
const next = splitMessageText(text, limit)[0] ?? initialText;
inFlight = Promise.resolve(next === lastSent ? undefined : edit(messageId, next))
.then(() => { lastSent = next; })
.catch((error) => logger.warn?.('[dsh-im] streamed message update failed:', error))
.finally(() => {
inFlight = null;
schedule();
});
}, updateIntervalMs);
timer?.unref?.();
};
return {
async start() {
messageId = await create(initialText);
return this;
},
update(text) {
if (closed || typeof text !== 'string' || !text.trim()) return;
pending = text;
schedule();
},
async finish(text) {
if (closed) throw new Error('Message stream is already closed');
closed = true;
if (timer !== null) clearTimeout(timer);
timer = null;
pending = null;
await inFlight?.catch(() => undefined);
const chunks = splitMessageText(text, limit);
const first = chunks[0] ?? '处理完成。';
if (first !== lastSent) await edit(messageId, first);
lastSent = first;
for (const chunk of chunks.slice(1)) await sendRemainder(chunk);
},
cancel() {
closed = true;
pending = null;
if (timer !== null) clearTimeout(timer);
timer = null;
},
};
}

View file

@ -0,0 +1,180 @@
function cleanText(value) {
return typeof value === 'string' ? value.trim() : '';
}
export function createTextBridgeStatus() {
return {
messagesReceived: 0,
messagesReplied: 0,
messagesRejected: 0,
lastMessageAt: null,
lastReplyAt: null,
lastRejectedAt: null,
lastError: null,
};
}
export class TextHarnessBridge {
#descriptor;
#bot;
#harness;
#state;
#status;
#logger;
#replyTimeoutMs;
#queues = new Map();
constructor({
descriptor,
bot,
harness,
state,
status = createTextBridgeStatus(),
logger = console,
replyTimeoutMs = 600_000,
}) {
if (!descriptor?.key || !descriptor?.label) throw new TypeError('A channel descriptor is required');
if (!bot || typeof bot.sendText !== 'function') throw new TypeError('A bot client is required');
if (!harness || !state) throw new TypeError('Harness client and state store are required');
this.#descriptor = descriptor;
this.#bot = bot;
this.#harness = harness;
this.#state = state;
this.#status = status;
this.#logger = logger;
this.#replyTimeoutMs = replyTimeoutMs;
}
get status() {
return structuredClone(this.#status);
}
accept(message) {
const conversationId = cleanText(message?.conversationId);
const kind = message?.kind === 'group' ? 'group' : 'direct';
const key = `${kind}:${conversationId}`;
const previous = this.#queues.get(key) ?? Promise.resolve();
const current = previous
.catch(() => undefined)
.then(() => this.#process({ ...message, kind, conversationId }))
.finally(() => {
if (this.#queues.get(key) === current) this.#queues.delete(key);
});
this.#queues.set(key, current);
return current;
}
async waitForIdle() {
await Promise.allSettled([...this.#queues.values()]);
}
async #process(message) {
const messageId = cleanText(message.messageId);
const senderId = cleanText(message.senderId);
if (!messageId || !senderId || !message.conversationId || message.senderIsBot === true) return;
if (this.#state.hasSeen(messageId)) return;
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
if (message.kind === 'group' && message.addressed !== true) {
this.#status.messagesRejected += 1;
this.#status.lastRejectedAt = new Date().toISOString();
return;
}
const target = message.replyTarget;
const text = cleanText(message.content);
try {
if (!text) {
await this.#bot.sendText(target, '目前仅支持文字消息。');
await this.#state.markSeen(messageId);
return;
}
const command = text.toLowerCase();
if (command === '/help') {
await this.#bot.sendText(target, [
`${this.#descriptor.label}机器人已连接 DeepSeek Harness。`,
'',
'直接发送文字即可继续当前会话。',
'/new 开启一个全新会话',
'/status 检查连接状态',
'/help 显示本帮助',
].join('\n'));
await this.#state.markSeen(messageId);
return;
}
if (command === '/status') {
await this.#harness.ensureRunning();
await this.#bot.sendText(target, `${this.#descriptor.label}机器人与 DeepSeek Harness 连接正常。`);
await this.#state.markSeen(messageId);
return;
}
const conversationKey = `${message.kind}:${message.conversationId}`;
if (command === '/new') {
await this.#state.clearSession(conversationKey);
await this.#bot.sendText(target, '已开启新会话。请发送你的问题。');
await this.#state.markSeen(messageId);
return;
}
let sessionId = this.#state.sessionFor(conversationKey);
if (!sessionId || !(await this.#harness.sessionExists(sessionId))) {
sessionId = await this.#harness.createSession();
await this.#state.setSession(conversationKey, sessionId);
}
await this.#bot.sendTyping?.(target).catch((error) => {
this.#logger.warn?.(`[dsh-im:${this.#descriptor.key}] typing indicator failed:`, error);
});
let stream = null;
let streamFinished = false;
if (typeof this.#bot.openStream === 'function') {
try {
stream = await this.#bot.openStream(target);
} catch (error) {
this.#logger.warn?.(
`[dsh-im:${this.#descriptor.key}] unable to start a streamed reply; using text:`,
error,
);
}
}
const answer = await this.#harness.ask(sessionId, text, {
timeoutMs: this.#replyTimeoutMs,
onUpdate: stream ? async (update) => {
const progress = update.type === 'text' ? update.text
: update.type === 'tool' ? `正在使用${update.name}…` : update.text;
if (progress) await stream.update(progress);
} : undefined,
});
if (stream) {
try {
await stream.finish(answer);
streamFinished = true;
} catch (error) {
stream.cancel?.();
this.#logger.warn?.(
`[dsh-im:${this.#descriptor.key}] streamed reply finalization failed; using text:`,
error,
);
}
}
if (!streamFinished) await this.#bot.sendText(target, answer);
await this.#state.markSeen(messageId);
this.#status.messagesReplied += 1;
this.#status.lastReplyAt = new Date().toISOString();
this.#status.lastError = null;
} catch (error) {
this.#status.lastError = error?.message ?? String(error);
this.#logger.error?.(`[dsh-im:${this.#descriptor.key}] failed to process a message:`, error);
try {
await this.#bot.sendText(target, '消息处理失败,请稍后重试。');
await this.#state.markSeen(messageId);
} catch (sendError) {
this.#logger.error?.(
`[dsh-im:${this.#descriptor.key}] failed to send the safe error reply:`,
sendError,
);
}
}
}
}

View file

@ -0,0 +1,298 @@
function cleanString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function safeError(code, message) {
return Object.freeze({ code, message });
}
export class TokenBotController {
#descriptor;
#credentials;
#configStore;
#inspectToken;
#deriveIdentity;
#maskPlatformId;
#createRuntime;
#deleteState;
#logger;
#runtimes = new Map();
#errors = new Map();
#transitions = new Map();
#revision = 0;
#closed = false;
constructor({
descriptor,
credentials,
configStore,
inspectToken,
deriveIdentity,
maskPlatformId,
createRuntime,
deleteState = async () => {},
logger = console,
}) {
if (!descriptor?.key || !descriptor?.label || !descriptor?.connectionLabel) {
throw new TypeError('TokenBotController requires a channel descriptor');
}
if (!credentials || typeof credentials.resolve !== 'function'
|| typeof credentials.set !== 'function' || typeof credentials.unset !== 'function') {
throw new TypeError(`${descriptor.label} requires the DSH credential provider`);
}
if (!configStore || typeof configStore.list !== 'function'
|| typeof configStore.save !== 'function' || typeof configStore.remove !== 'function') {
throw new TypeError(`${descriptor.label} requires a config store`);
}
if (typeof inspectToken !== 'function' || typeof deriveIdentity !== 'function'
|| typeof maskPlatformId !== 'function' || typeof createRuntime !== 'function') {
throw new TypeError(`${descriptor.label} controller dependencies are incomplete`);
}
this.#descriptor = descriptor;
this.#credentials = credentials;
this.#configStore = configStore;
this.#inspectToken = inspectToken;
this.#deriveIdentity = deriveIdentity;
this.#maskPlatformId = maskPlatformId;
this.#createRuntime = createRuntime;
this.#deleteState = deleteState;
this.#logger = logger;
}
async initialize() {
if (this.#closed) return this.status();
for (const config of this.#configStore.list()) {
await this.#withBotTransition(config.botId, async () => {
if (this.#closed || this.#runtimes.get(config.botId)?.status?.ready) return;
const token = await this.#resolveToken(config.tokenRef);
if (!token) {
this.#errors.set(config.botId, safeError(
'missing-token',
`${this.#descriptor.label}机器人凭据缺失,请移除后重新接入。`,
));
return;
}
try {
await this.#startRuntime(config, token);
this.#errors.delete(config.botId);
} catch (error) {
this.#errors.set(config.botId, safeError(
'connection-failed',
`${this.#descriptor.label}连接未就绪,插件会自动重试。`,
));
this.#logger.warn?.(
`[dsh-im:${this.#descriptor.key}] bot ${config.botId} failed to initialize:`,
error,
);
} finally {
this.#touch();
}
});
}
return this.status();
}
async bindCredentials({ token } = {}) {
if (this.#closed) throw new Error(`${this.#descriptor.label} controller is closed`);
const normalizedToken = cleanString(token);
if (!normalizedToken) throw new TypeError(`${this.#descriptor.label} Bot Token is required`);
const inspected = await this.#inspectToken(normalizedToken);
const platformId = cleanString(inspected?.platformId);
const name = cleanString(inspected?.name);
if (!platformId || !name) throw new Error(`${this.#descriptor.label} returned an invalid bot identity`);
const identity = this.#deriveIdentity(platformId);
await this.#withBotTransition(identity.botId, async () => {
if (this.#closed) throw new Error(`${this.#descriptor.label} controller is closed`);
const previousConfig = this.#configStore.getByPlatformId(platformId);
const previousToken = await this.#credentials.resolve(identity.tokenRef).catch(() => undefined);
const config = {
botId: identity.botId,
platformId,
tokenRef: identity.tokenRef,
name,
username: cleanString(inspected.username),
createdAt: previousConfig?.createdAt ?? new Date().toISOString(),
connectedAt: new Date().toISOString(),
};
await this.#credentials.set(identity.tokenRef, normalizedToken);
try {
await this.#configStore.save(config);
} catch (error) {
await this.#restoreCredential(identity.tokenRef, previousToken);
throw error;
}
try {
await this.#startRuntime(config, normalizedToken);
this.#errors.delete(identity.botId);
} catch (error) {
this.#errors.set(identity.botId, safeError(
'connection-failed',
`${this.#descriptor.label}机器人已接入,消息连接暂未就绪。`,
));
this.#logger.warn?.(
`[dsh-im:${this.#descriptor.key}] bot ${identity.botId} credential connection failed:`,
error,
);
}
this.#touch();
});
return this.status();
}
async reconnectBot(botId) {
const config = this.#configStore.get(botId);
if (!config) throw new Error(`Unknown ${this.#descriptor.label} bot`);
await this.#withBotTransition(botId, async () => {
const token = await this.#resolveToken(config.tokenRef);
if (!token) throw new Error(`${this.#descriptor.label} bot token is missing`);
try {
await this.#startRuntime(config, token);
this.#errors.delete(botId);
} catch (error) {
this.#errors.set(botId, safeError(
'connection-failed',
`${this.#descriptor.label}连接仍未就绪,请稍后重试。`,
));
throw error;
} finally {
this.#touch();
}
});
return this.status();
}
async deleteBot(botId) {
const config = this.#configStore.get(botId);
if (!config) throw new Error(`Unknown ${this.#descriptor.label} bot`);
await this.#withBotTransition(botId, async () => {
const previous = await this.#credentials.resolve(config.tokenRef).catch(() => undefined);
await this.#stopRuntime(botId);
try {
await this.#credentials.unset(config.tokenRef);
await this.#configStore.remove(botId);
} catch (error) {
if (previous?.value) {
await this.#credentials.set(config.tokenRef, previous.value).catch(() => undefined);
await this.#startRuntime(config, previous.value).catch(() => undefined);
}
throw new Error(`Unable to remove the ${this.#descriptor.label} bot safely.`, { cause: error });
}
await this.#deleteState({ botId, config }).catch((error) => {
this.#logger.warn?.(
`[dsh-im:${this.#descriptor.key}] bot ${botId} state cleanup failed:`,
error,
);
});
this.#errors.delete(botId);
this.#touch();
});
return this.status();
}
status() {
const bots = this.#configStore.list().map((config) => {
const runtimeStatus = this.#runtimes.get(config.botId)?.status ?? null;
const connected = runtimeStatus?.ready === true
&& runtimeStatus.connectionState === 'connected'
&& runtimeStatus.harnessReachable === true;
const state = connected ? 'connected'
: runtimeStatus?.connectionState === 'connecting' ? 'connecting'
: this.#errors.has(config.botId) || runtimeStatus?.connectionState === 'failed'
? 'error' : 'offline';
return {
botId: config.botId,
state,
connected,
configured: true,
bot: {
name: config.name,
username: config.username,
idMasked: this.#maskPlatformId(config.platformId),
},
health: {
status: connected ? 'healthy' : state === 'error' ? 'error' : 'offline',
summary: connected ? `${this.#descriptor.label}${this.#descriptor.connectionLabel}运行正常`
: state === 'error' ? `${this.#descriptor.label}连接未就绪,插件会自动重试`
: `${this.#descriptor.label}连接当前离线`,
lastCheckedAt: runtimeStatus?.lastCheckedAt ?? null,
lastConnectedAt: runtimeStatus?.lastConnectedAt ?? null,
},
stats: {
messagesReceived: runtimeStatus?.messagesReceived ?? 0,
messagesReplied: runtimeStatus?.messagesReplied ?? 0,
},
error: structuredClone(this.#errors.get(config.botId) ?? null),
};
});
const connectedCount = bots.filter((bot) => bot.connected).length;
return {
schemaVersion: 1,
revision: this.#revision,
state: bots.length === 0 ? 'disconnected'
: connectedCount === bots.length ? 'connected'
: connectedCount > 0 ? 'degraded' : 'offline',
bots,
totals: { configured: bots.length, connected: connectedCount },
};
}
async close() {
if (this.#closed) return;
this.#closed = true;
await Promise.allSettled([...this.#transitions.values()]);
await Promise.allSettled([...this.#runtimes.keys()].map((botId) => this.#stopRuntime(botId)));
}
async #startRuntime(config, token) {
if (this.#closed) throw new Error(`${this.#descriptor.label} controller is closed`);
await this.#stopRuntime(config.botId);
if (this.#closed) throw new Error(`${this.#descriptor.label} controller is closed`);
const runtime = await this.#createRuntime({ botId: config.botId, config, token });
if (!runtime || typeof runtime.start !== 'function' || typeof runtime.stop !== 'function') {
throw new TypeError(`createRuntime returned an invalid ${this.#descriptor.label} runtime`);
}
this.#runtimes.set(config.botId, runtime);
try {
await runtime.start();
} catch (error) {
await runtime.stop().catch(() => undefined);
this.#runtimes.delete(config.botId);
throw error;
}
}
async #stopRuntime(botId) {
const runtime = this.#runtimes.get(botId);
this.#runtimes.delete(botId);
await runtime?.stop().catch((error) => {
this.#logger.warn?.(
`[dsh-im:${this.#descriptor.key}] bot ${botId} failed to stop cleanly:`,
error,
);
});
}
async #resolveToken(ref) {
const result = await this.#credentials.resolve(ref).catch(() => undefined);
return cleanString(result?.value);
}
async #restoreCredential(ref, previous) {
if (previous?.value) await this.#credentials.set(ref, previous.value).catch(() => undefined);
else await this.#credentials.unset(ref).catch(() => undefined);
}
#withBotTransition(botId, operation) {
const previous = this.#transitions.get(botId) ?? Promise.resolve();
const current = previous.catch(() => undefined).then(operation);
const settled = current.finally(() => {
if (this.#transitions.get(botId) === settled) this.#transitions.delete(botId);
});
this.#transitions.set(botId, settled);
return settled;
}
#touch() {
this.#revision += 1;
}
}

View file

@ -0,0 +1,180 @@
import { createHash } from 'node:crypto';
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
const EMPTY_DOCUMENT = Object.freeze({ version: 1, bots: Object.freeze([]) });
function cleanString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function escapePattern(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
export function deriveTokenBotIdentity(platformId, { botPrefix, tokenRefPrefix }) {
const raw = cleanString(platformId);
if (!raw) throw new TypeError('platformId is required');
const digest = createHash('sha256').update(raw).digest('hex').slice(0, 24);
return {
botId: `${botPrefix}_${digest}`,
tokenRef: `${tokenRefPrefix}_${digest.toUpperCase()}`,
};
}
export function maskPlatformId(platformId, fallback) {
const value = cleanString(platformId) ?? '';
if (value.length <= 10) return value ? `${value.slice(0, 3)}•••` : fallback;
return `${value.slice(0, 6)}••••${value.slice(-4)}`;
}
export class TokenBotConfigStore {
#path;
#channel;
#botPrefix;
#tokenRefPrefix;
#botIdPattern;
#tokenRefPattern;
#value = EMPTY_DOCUMENT;
#writeQueue = Promise.resolve();
constructor(path, { channel, botPrefix, tokenRefPrefix }) {
this.#path = path;
this.#channel = channel;
this.#botPrefix = botPrefix;
this.#tokenRefPrefix = tokenRefPrefix;
this.#botIdPattern = new RegExp(`^${escapePattern(botPrefix)}_[a-f0-9]{24}$`);
this.#tokenRefPattern = new RegExp(`^${escapePattern(tokenRefPrefix)}_[A-F0-9]{24}$`);
}
async load() {
try {
const normalized = this.#normalizeDocument(JSON.parse(await readFile(this.#path, 'utf8')));
if (!normalized) throw new Error(`dsh-im ${this.#channel} config contains invalid bot data`);
this.#value = normalized;
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
this.#value = EMPTY_DOCUMENT;
}
return this;
}
list() {
return structuredClone(this.#value.bots);
}
get(botId) {
const bot = this.#value.bots.find((candidate) => candidate.botId === botId);
return bot ? structuredClone(bot) : null;
}
getByPlatformId(platformId) {
const bot = this.#value.bots.find((candidate) => candidate.platformId === platformId);
return bot ? structuredClone(bot) : null;
}
async save(value) {
const normalized = this.#normalizeBot(value);
if (!normalized) throw new Error(`Refusing to persist incomplete ${this.#channel} bot data`);
return this.#mutate((bots) => {
const identityCollision = bots.find(
(bot) => bot.platformId === normalized.platformId && bot.botId !== normalized.botId,
);
const refCollision = bots.find(
(bot) => bot.tokenRef === normalized.tokenRef && bot.botId !== normalized.botId,
);
if (identityCollision || refCollision) throw new Error(`Duplicate ${this.#channel} bot identity`);
const index = bots.findIndex((bot) => bot.botId === normalized.botId);
if (index === -1) bots.push(normalized);
else bots[index] = normalized;
return structuredClone(normalized);
});
}
async remove(botId) {
if (!this.#botIdPattern.test(botId)) throw new TypeError(`Invalid ${this.#channel} bot id`);
return this.#mutate((bots) => {
const index = bots.findIndex((bot) => bot.botId === botId);
if (index === -1) return null;
const [removed] = bots.splice(index, 1);
return structuredClone(removed);
});
}
async clear() {
const operation = this.#writeQueue.then(async () => {
try {
await unlink(this.#path);
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
}
this.#value = EMPTY_DOCUMENT;
});
this.#writeQueue = operation.then(() => undefined, () => undefined);
await operation;
}
#normalizeBot(value) {
if (!value || typeof value !== 'object') return null;
const platformId = cleanString(value.platformId);
const botId = cleanString(value.botId);
const tokenRef = cleanString(value.tokenRef);
const name = cleanString(value.name);
if (!platformId || !botId || !tokenRef || !name
|| !this.#botIdPattern.test(botId) || !this.#tokenRefPattern.test(tokenRef)) return null;
const derived = deriveTokenBotIdentity(platformId, {
botPrefix: this.#botPrefix,
tokenRefPrefix: this.#tokenRefPrefix,
});
if (derived.botId !== botId || derived.tokenRef !== tokenRef) return null;
return Object.freeze({
botId,
platformId,
tokenRef,
name,
username: cleanString(value.username),
createdAt: cleanString(value.createdAt) ?? new Date().toISOString(),
connectedAt: cleanString(value.connectedAt),
});
}
#normalizeDocument(value) {
if (!value || value.version !== 1 || !Array.isArray(value.bots)) return null;
const bots = value.bots.map((bot) => this.#normalizeBot(bot));
if (bots.some((bot) => bot === null)) return null;
const ids = new Set();
const platformIds = new Set();
const refs = new Set();
for (const bot of bots) {
if (ids.has(bot.botId) || platformIds.has(bot.platformId) || refs.has(bot.tokenRef)) return null;
ids.add(bot.botId);
platformIds.add(bot.platformId);
refs.add(bot.tokenRef);
}
return Object.freeze({ version: 1, bots: Object.freeze(bots) });
}
async #mutate(mutator) {
let result;
const operation = this.#writeQueue.then(async () => {
const bots = [...this.#value.bots];
result = mutator(bots);
const document = Object.freeze({ version: 1, bots: Object.freeze(bots) });
await this.#write(document);
this.#value = document;
});
this.#writeQueue = operation.then(() => undefined, () => undefined);
await operation;
return result;
}
async #write(document) {
await mkdir(dirname(this.#path), { recursive: true, mode: 0o700 });
const temporary = `${this.#path}.tmp`;
await writeFile(temporary, `${JSON.stringify(document, null, 2)}\n`, {
encoding: 'utf8',
mode: 0o600,
});
await rename(temporary, this.#path);
}
}

View file

@ -0,0 +1,24 @@
import {
deriveTokenBotIdentity,
maskPlatformId,
TokenBotConfigStore,
} from '../shared/token-config-store.mjs';
const IDENTITY_OPTIONS = Object.freeze({
botPrefix: 'telegram',
tokenRefPrefix: 'DSH_TELEGRAM_BOT_TOKEN',
});
export function deriveTelegramBotIdentity(platformId) {
return deriveTokenBotIdentity(platformId, IDENTITY_OPTIONS);
}
export function maskTelegramBotId(platformId) {
return maskPlatformId(platformId, 'Telegram机器人');
}
export class TelegramConfigStore extends TokenBotConfigStore {
constructor(path) {
super(path, { channel: 'Telegram', ...IDENTITY_OPTIONS });
}
}

View file

@ -0,0 +1,3 @@
import { HarnessClient } from '../weixin/harness-client.mjs';
export class TelegramHarnessClient extends HarnessClient {}

View file

@ -0,0 +1,3 @@
import { ConversationStateStore } from '../shared/conversation-state-store.mjs';
export class TelegramStateStore extends ConversationStateStore {}

View file

@ -0,0 +1,120 @@
const DEFAULT_BASE_URL = 'https://api.telegram.org/';
function cleanString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function requestSignal(signal, timeoutMs) {
const timeout = AbortSignal.timeout(timeoutMs);
return signal ? AbortSignal.any([signal, timeout]) : timeout;
}
export function validTelegramToken(value) {
return typeof value === 'string' && /^\d{5,20}:[A-Za-z0-9_-]{20,}$/.test(value.trim());
}
export class TelegramApi {
#token;
#fetch;
#baseUrl;
constructor({ token, fetchImpl = fetch, baseUrl = DEFAULT_BASE_URL }) {
if (!validTelegramToken(token)) throw new TypeError('Telegram Bot Token is invalid');
if (typeof fetchImpl !== 'function') throw new TypeError('TelegramApi requires fetch');
this.#token = token.trim();
this.#fetch = fetchImpl;
this.#baseUrl = new URL(baseUrl);
}
async getMe(options = {}) {
return this.#call('getMe', {}, options);
}
async getWebhookInfo(options = {}) {
return this.#call('getWebhookInfo', {}, options);
}
async getUpdates({ offset, timeout = 25, signal } = {}) {
const payload = {
timeout,
limit: 100,
allowed_updates: ['message'],
...(Number.isSafeInteger(offset) ? { offset } : {}),
};
return this.#call('getUpdates', payload, {
signal,
timeoutMs: Math.max(10_000, (timeout + 10) * 1_000),
});
}
async sendMessage({ chatId, text, replyToMessageId, messageThreadId, signal }) {
return this.#call('sendMessage', {
chat_id: chatId,
text,
link_preview_options: { is_disabled: true },
...(replyToMessageId ? {
reply_parameters: { message_id: replyToMessageId, allow_sending_without_reply: true },
} : {}),
...(messageThreadId ? { message_thread_id: messageThreadId } : {}),
}, { signal });
}
async editMessageText({ chatId, messageId, text, signal }) {
return this.#call('editMessageText', {
chat_id: chatId,
message_id: messageId,
text,
link_preview_options: { is_disabled: true },
}, { signal });
}
async sendChatAction({ chatId, messageThreadId, signal }) {
return this.#call('sendChatAction', {
chat_id: chatId,
action: 'typing',
...(messageThreadId ? { message_thread_id: messageThreadId } : {}),
}, { signal });
}
async #call(method, payload, { signal, timeoutMs = 15_000 } = {}) {
const url = new URL(this.#baseUrl);
url.pathname = `${url.pathname.replace(/\/$/, '')}/bot${this.#token}/${method}`;
let response;
try {
response = await this.#fetch(url, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload),
signal: requestSignal(signal, timeoutMs),
redirect: 'error',
});
} catch (error) {
if (error?.name === 'AbortError' || error?.name === 'TimeoutError') throw error;
throw new Error(`Telegram ${method} transport failed`);
}
let body;
try {
body = await response.json();
} catch {
throw new Error(`Telegram ${method} returned invalid JSON`);
}
if (!response.ok || body?.ok !== true) {
const description = cleanString(body?.description);
const error = new Error(description ?? `Telegram ${method} failed`);
error.code = Number.isInteger(body?.error_code) ? `telegram-${body.error_code}` : 'telegram-api-error';
throw error;
}
return body.result;
}
}
export async function inspectTelegramToken(token, options = {}) {
const api = new TelegramApi({ token, ...options });
const bot = await api.getMe();
if (!bot?.id || bot?.is_bot !== true) throw new Error('Telegram token does not belong to a bot');
return {
platformId: String(bot.id),
name: cleanString([bot.first_name, bot.last_name].filter(Boolean).join(' ')) ?? 'Telegram机器人',
username: cleanString(bot.username),
};
}

View file

@ -0,0 +1,15 @@
import { TextHarnessBridge, createTextBridgeStatus } from '../shared/text-harness-bridge.mjs';
export const TELEGRAM_DESCRIPTOR = Object.freeze({
key: 'telegram',
label: 'Telegram',
connectionLabel: ' Bot API 长轮询',
});
export class TelegramHarnessBridge extends TextHarnessBridge {
constructor(options) {
super({ descriptor: TELEGRAM_DESCRIPTOR, ...options });
}
}
export { createTextBridgeStatus as createTelegramBridgeStatus };

View file

@ -0,0 +1,16 @@
import { TokenBotController } from '../shared/token-bot-controller.mjs';
import { deriveTelegramBotIdentity, maskTelegramBotId } from './config-store.mjs';
import { inspectTelegramToken } from './telegram-api.mjs';
import { TELEGRAM_DESCRIPTOR } from './telegram-bridge.mjs';
export class TelegramController extends TokenBotController {
constructor(options) {
super({
...options,
descriptor: TELEGRAM_DESCRIPTOR,
inspectToken: options.inspectToken ?? inspectTelegramToken,
deriveIdentity: deriveTelegramBotIdentity,
maskPlatformId: maskTelegramBotId,
});
}
}

View file

@ -0,0 +1,278 @@
import { createEditableMessageStream, splitMessageText } from '../shared/editable-message-stream.mjs';
import { TelegramApi } from './telegram-api.mjs';
import { createTelegramBridgeStatus, TelegramHarnessBridge } from './telegram-bridge.mjs';
function escaped(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function mentionedUsername(message, username) {
if (!username || typeof message?.text !== 'string' || !Array.isArray(message.entities)) return false;
return message.entities.some((entity) => {
if (entity?.type !== 'mention' || !Number.isInteger(entity.offset) || !Number.isInteger(entity.length)) {
return false;
}
return message.text.slice(entity.offset, entity.offset + entity.length).toLowerCase()
=== `@${username.toLowerCase()}`;
});
}
function withoutBotMention(text, username) {
if (!username || typeof text !== 'string') return text;
return text.replace(new RegExp(`@${escaped(username)}\\b`, 'ig'), '').trim();
}
export function normalizeTelegramUpdate(update, { botId, username }) {
const message = update?.message;
const chatId = message?.chat?.id;
const senderId = message?.from?.id;
const messageId = message?.message_id;
if (!Number.isSafeInteger(update?.update_id) || chatId === undefined || senderId === undefined
|| !Number.isSafeInteger(messageId)) return null;
if (!['private', 'group', 'supergroup'].includes(message.chat?.type)) return null;
const direct = message.chat.type === 'private';
const addressed = direct
|| String(message.reply_to_message?.from?.id ?? '') === String(botId)
|| mentionedUsername(message, username);
return {
messageId: String(update.update_id),
senderId: String(senderId),
senderIsBot: message.from?.is_bot === true,
kind: direct ? 'direct' : 'group',
conversationId: String(chatId),
content: withoutBotMention(message.text ?? message.caption ?? '', username),
addressed,
replyTarget: {
chatId,
replyToMessageId: messageId,
messageThreadId: Number.isSafeInteger(message.message_thread_id)
? message.message_thread_id : undefined,
},
};
}
class TelegramBotClient {
#api;
#signal;
constructor({ api, signal }) {
this.#api = api;
this.#signal = signal;
}
async sendText(target, text) {
const chunks = splitMessageText(text, 4_000);
let result = null;
for (const [index, chunk] of chunks.entries()) {
result = await this.#api.sendMessage({
chatId: target.chatId,
text: chunk,
replyToMessageId: index === 0 ? target.replyToMessageId : undefined,
messageThreadId: target.messageThreadId,
signal: this.#signal,
});
}
return result;
}
sendTyping(target) {
return this.#api.sendChatAction({
chatId: target.chatId,
messageThreadId: target.messageThreadId,
signal: this.#signal,
});
}
async openStream(target) {
const stream = createEditableMessageStream({
limit: 4_000,
create: async (text) => {
const message = await this.#api.sendMessage({
chatId: target.chatId,
text,
replyToMessageId: target.replyToMessageId,
messageThreadId: target.messageThreadId,
signal: this.#signal,
});
return message.message_id;
},
edit: (messageId, text) => this.#api.editMessageText({
chatId: target.chatId,
messageId,
text,
signal: this.#signal,
}),
sendRemainder: (text) => this.#api.sendMessage({
chatId: target.chatId,
text,
messageThreadId: target.messageThreadId,
signal: this.#signal,
}),
});
return stream.start();
}
}
export function createTelegramRuntimeStatus() {
return {
startedAt: null,
ready: false,
connectionState: 'idle',
harnessReachable: false,
lastCheckedAt: null,
lastConnectedAt: null,
lastError: null,
...createTelegramBridgeStatus(),
};
}
export class TelegramRuntime {
#config;
#token;
#harness;
#state;
#logger;
#replyTimeoutMs;
#createApi;
#status = createTelegramRuntimeStatus();
#api = null;
#bridge = null;
#abortController = null;
#pollTask = null;
#starting = null;
constructor({
config,
token,
harness,
state,
logger = console,
replyTimeoutMs = 600_000,
createApi = (options) => new TelegramApi(options),
}) {
if (!config || !token || !harness || !state) {
throw new TypeError('TelegramRuntime requires config, token, Harness, and state');
}
this.#config = config;
this.#token = token;
this.#harness = harness;
this.#state = state;
this.#logger = logger;
this.#replyTimeoutMs = replyTimeoutMs;
this.#createApi = createApi;
}
get status() {
return structuredClone(this.#status);
}
async start() {
if (this.#status.ready && this.#pollTask) return this.status;
if (this.#starting) return this.#starting;
this.#starting = this.#start().finally(() => {
this.#starting = null;
});
return this.#starting;
}
async #start() {
await this.stop();
this.#status.startedAt = new Date().toISOString();
this.#status.connectionState = 'connecting';
this.#status.lastError = null;
await this.#harness.ensureRunning();
this.#status.harnessReachable = true;
const controller = new AbortController();
this.#abortController = controller;
const api = this.#createApi({ token: this.#token });
this.#api = api;
try {
const bot = await api.getMe({ signal: controller.signal });
if (String(bot?.id ?? '') !== this.#config.platformId || bot?.is_bot !== true) {
throw new Error('Telegram token identity does not match the saved bot');
}
const webhook = await api.getWebhookInfo({ signal: controller.signal });
if (typeof webhook?.url === 'string' && webhook.url) {
const error = new Error('该 Telegram 机器人已配置 Webhook,请先在原服务中移除 Webhook 后重试。');
error.code = 'webhook-configured';
throw error;
}
const client = new TelegramBotClient({ api, signal: controller.signal });
this.#bridge = new TelegramHarnessBridge({
bot: client,
harness: this.#harness,
state: this.#state,
status: this.#status,
logger: this.#logger,
replyTimeoutMs: this.#replyTimeoutMs,
});
let cursor = this.#state.cursor();
if (cursor === null) {
const latest = await api.getUpdates({ offset: -1, timeout: 0, signal: controller.signal });
cursor = latest.length > 0 ? latest.at(-1).update_id + 1 : 0;
await this.#state.setCursor(cursor);
}
const now = Date.now();
this.#status.ready = true;
this.#status.connectionState = 'connected';
this.#status.lastCheckedAt = now;
this.#status.lastConnectedAt = now;
this.#pollTask = this.#poll(cursor, controller.signal);
this.#pollTask.catch((error) => {
if (controller.signal.aborted) return;
this.#status.ready = false;
this.#status.connectionState = 'failed';
this.#status.lastError = error?.message ?? String(error);
this.#logger.error?.(`[dsh-im:telegram] bot ${this.#config.botId} polling stopped:`, error);
});
return this.status;
} catch (error) {
this.#status.ready = false;
this.#status.connectionState = 'failed';
this.#status.lastError = error?.message ?? String(error);
await this.stop();
throw error;
}
}
async #poll(initialCursor, signal) {
let cursor = initialCursor;
while (!signal.aborted) {
const updates = await this.#api.getUpdates({ offset: cursor, timeout: 25, signal });
this.#status.lastCheckedAt = Date.now();
for (const update of updates) {
if (signal.aborted) return;
const message = normalizeTelegramUpdate(update, {
botId: this.#config.platformId,
username: this.#config.username,
});
if (message) await this.#bridge.accept(message);
cursor = update.update_id + 1;
await this.#state.setCursor(cursor);
}
}
}
async stop() {
const pollTask = this.#pollTask;
const bridge = this.#bridge;
this.#abortController?.abort();
this.#abortController = null;
this.#pollTask = null;
this.#api = null;
this.#bridge = null;
await Promise.race([
pollTask?.catch(() => undefined) ?? Promise.resolve(),
new Promise((resolve) => setTimeout(resolve, 2_000)),
]);
await Promise.race([
bridge?.waitForIdle() ?? Promise.resolve(),
new Promise((resolve) => setTimeout(resolve, 2_000)),
]);
this.#status.ready = false;
this.#status.connectionState = 'idle';
return this.status;
}
}