@xmanrui/dsh-im 5.3.0 → 5.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/PROACTIVE_DELIVERY.en.md +15 -0
- package/PROACTIVE_DELIVERY.md +15 -0
- package/README.en.md +44 -3
- package/README.md +44 -3
- package/THIRD_PARTY_NOTICES.md +209 -0
- package/docs/client-integration.md +2 -2
- package/lib/client.js +3737 -433
- package/lib/index.js +415 -344
- package/package.json +1 -1
- package/plugin-src/client/channel-card-meta.js +6 -2
- package/plugin-src/client/channels/shared/token-api.js +13 -0
- package/plugin-src/client/channels/telegram/group-triggers-settings.js +393 -0
- package/plugin-src/client/channels/telegram/styles.js +4 -0
- package/plugin-src/client/channels/telegram/thinking-traces.js +138 -5
- package/plugin-src/client/delivery-settings.js +23 -3
- package/plugin-src/client/ds-bot-avatar-data.js +537 -0
- package/plugin-src/client/ds-bot-avatar.js +55 -0
- package/plugin-src/client/ds-bot-session-avatars.js +77 -0
- package/plugin-src/client/ds-bot-settings.js +194 -0
- package/plugin-src/client/i18n-ru.js +1615 -0
- package/plugin-src/client/i18n.js +130 -1
- package/plugin-src/client/index.js +20 -2
- package/plugin-src/client/plugin-page.js +3 -8
- package/plugin-src/client/styles.js +25 -5
- package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
- package/plugin-src/host/channels/feishu/production.mjs +13 -5
- package/plugin-src/host/channels/qq/production.mjs +2 -1
- package/plugin-src/host/channels/shared/group-triggers-rpc.mjs +110 -0
- package/plugin-src/host/channels/shared/production.mjs +12 -1
- package/plugin-src/host/channels/shared/rpc.mjs +21 -0
- package/plugin-src/host/channels/shared/send-limit-rpc.mjs +13 -0
- package/plugin-src/host/channels/shared/thinking-cadence-rpc.mjs +16 -0
- package/plugin-src/host/channels/slack/production.mjs +2 -1
- package/plugin-src/host/channels/telegram/index.mjs +1 -0
- package/plugin-src/host/channels/telegram/production.mjs +9 -0
- package/plugin-src/host/channels/telegram/rpc.mjs +17 -2
- package/plugin-src/host/channels/wecom/production.mjs +4 -1
- package/plugin-src/host/channels/wecom-app/production.mjs +2 -1
- package/plugin-src/host/channels/weixin/production.mjs +2 -1
- package/plugin-src/host/channels/whatsapp/production.mjs +2 -1
- package/plugin-src/host/delivery-adapter.mjs +129 -41
- package/plugin-src/host/delivery-rpc.mjs +33 -1
- package/plugin-src/host/delivery-service.mjs +112 -1
- package/plugin-src/host/delivery-suggestions.mjs +11 -0
- package/plugin-src/host/ds-bot-client.mjs +87 -0
- package/plugin-src/host/ds-bot-question-sync.mjs +78 -0
- package/plugin-src/host/index.mjs +8 -1
- package/plugin-src/host/modern-harness-api.mjs +53 -8
- package/plugin-src/host/session-sync-coordinator.mjs +5 -5
- package/scripts/verify-package.mjs +17 -5
- package/src/channels/feishu/bridge.mjs +83 -5
- package/src/channels/feishu/feishu-cards.mjs +11 -7
- package/src/channels/feishu/feishu-runtime.mjs +10 -0
- package/src/channels/feishu/multi-bot-controller.mjs +12 -0
- package/src/channels/shared/AGENTS.md +19 -0
- package/src/channels/shared/bot-workspace-store.mjs +136 -7
- package/src/channels/shared/clear-command.mjs +2 -1
- package/src/channels/shared/compact-command.mjs +2 -1
- package/src/channels/shared/conversation-queue.mjs +49 -0
- package/src/channels/shared/deferred-delivery-coordinator.mjs +2 -1
- package/src/channels/shared/group-history-store.mjs +26 -0
- package/src/channels/shared/harness-client.mjs +5 -4
- package/src/channels/shared/history-command.mjs +2 -1
- package/src/channels/shared/i18n-en/feishu.mjs +1 -0
- package/src/channels/shared/i18n-en/shared-a.mjs +2 -2
- package/src/channels/shared/i18n-en/shared-b.mjs +2 -2
- package/src/channels/shared/i18n-en/shared-c.mjs +3 -2
- package/src/channels/shared/i18n-en/wecom.mjs +4 -0
- package/src/channels/shared/i18n-ru/diagnostics.mjs +104 -0
- package/src/channels/shared/i18n-ru/dingtalk.mjs +96 -0
- package/src/channels/shared/i18n-ru/discord.mjs +10 -0
- package/src/channels/shared/i18n-ru/email.mjs +23 -0
- package/src/channels/shared/i18n-ru/feishu.mjs +374 -0
- package/src/channels/shared/i18n-ru/image-input.mjs +25 -0
- package/src/channels/shared/i18n-ru/matrix.mjs +73 -0
- package/src/channels/shared/i18n-ru/office.mjs +27 -0
- package/src/channels/shared/i18n-ru/permission.mjs +45 -0
- package/src/channels/shared/i18n-ru/qq.mjs +88 -0
- package/src/channels/shared/i18n-ru/shared-a.mjs +236 -0
- package/src/channels/shared/i18n-ru/shared-b.mjs +257 -0
- package/src/channels/shared/i18n-ru/shared-c.mjs +173 -0
- package/src/channels/shared/i18n-ru/slack.mjs +22 -0
- package/src/channels/shared/i18n-ru/telegram.mjs +25 -0
- package/src/channels/shared/i18n-ru/wecom-app.mjs +43 -0
- package/src/channels/shared/i18n-ru/wecom.mjs +79 -0
- package/src/channels/shared/i18n-ru/weixin.mjs +275 -0
- package/src/channels/shared/i18n-ru/whatsapp.mjs +18 -0
- package/src/channels/shared/i18n-ru.mjs +48 -0
- package/src/channels/shared/i18n.mjs +47 -12
- package/src/channels/shared/inbound-access.mjs +1 -1
- package/src/channels/shared/interface-language.mjs +3 -3
- package/src/channels/shared/message-failure.mjs +3 -2
- package/src/channels/shared/model-command.mjs +2 -1
- package/src/channels/shared/permission-command.mjs +2 -1
- package/src/channels/shared/send-limit.mjs +38 -0
- package/src/channels/shared/session-binding-lock.mjs +2 -0
- package/src/channels/shared/session-error.mjs +3 -0
- package/src/channels/shared/status-reaction.mjs +2 -0
- package/src/channels/shared/text-harness-bridge.mjs +4 -0
- package/src/channels/shared/thinking-cadence.mjs +36 -0
- package/src/channels/shared/workspace-command.mjs +2 -1
- package/src/channels/shared/workspace-session.mjs +5 -1
- package/src/channels/telegram/config-store.mjs +38 -1
- package/src/channels/telegram/group-triggers.mjs +229 -0
- package/src/channels/telegram/telegram-api.mjs +223 -32
- package/src/channels/telegram/telegram-bridge.mjs +4 -1
- package/src/channels/telegram/telegram-controller.mjs +139 -1
- package/src/channels/telegram/telegram-runtime.mjs +522 -178
- package/src/channels/telegram/voice.mjs +250 -0
- package/src/channels/wecom/stream-supervisor.mjs +184 -0
- package/src/channels/wecom/wecom-bridge.mjs +25 -11
- package/src/channels/wecom/wecom-runtime.mjs +12 -1
|
@@ -1,11 +1,19 @@
|
|
|
1
1
|
import { fetchFileStream } from '../shared/file-download.mjs';
|
|
2
2
|
import { fetchImageBuffer } from '../shared/image-prompt.mjs';
|
|
3
3
|
import { t } from '../shared/i18n.mjs';
|
|
4
|
+
import { DEFAULT_SEND_LIMIT_PER_MINUTE } from '../shared/send-limit.mjs';
|
|
4
5
|
|
|
5
6
|
const DEFAULT_BASE_URL = 'https://api.telegram.org/';
|
|
6
7
|
const TELEGRAM_FILE_HOSTS = Object.freeze(['api.telegram.org']);
|
|
7
8
|
const DEFAULT_FILE_UPLOAD_TIMEOUT_MS = 120_000;
|
|
8
9
|
|
|
10
|
+
/** Telegram budgets new messages per chat, so the window is not configurable. */
|
|
11
|
+
const SEND_WINDOW_MS = 60_000;
|
|
12
|
+
/** One original call plus three retries after 429. */
|
|
13
|
+
const MAX_SEND_ATTEMPTS = 4;
|
|
14
|
+
/** A 429 that asks for more than this is reported instead of waited out. */
|
|
15
|
+
const MAX_RATE_LIMIT_WAIT_MS = 60_000;
|
|
16
|
+
|
|
9
17
|
function cleanString(value) {
|
|
10
18
|
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
|
11
19
|
}
|
|
@@ -26,6 +34,36 @@ function positiveTimeout(value, name) {
|
|
|
26
34
|
return value;
|
|
27
35
|
}
|
|
28
36
|
|
|
37
|
+
/** Resolve after `ms`, or reject as soon as the caller aborts. */
|
|
38
|
+
function waitForDelay(ms, signal) {
|
|
39
|
+
if (!(ms > 0)) return Promise.resolve();
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
const onAbort = () => {
|
|
42
|
+
clearTimeout(timer);
|
|
43
|
+
reject(abortReason(signal));
|
|
44
|
+
};
|
|
45
|
+
const timer = setTimeout(() => {
|
|
46
|
+
signal?.removeEventListener?.('abort', onAbort);
|
|
47
|
+
resolve();
|
|
48
|
+
}, ms);
|
|
49
|
+
signal?.addEventListener?.('abort', onAbort, { once: true });
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Seconds Telegram asked us to wait, or null when the error is not a 429.
|
|
55
|
+
*
|
|
56
|
+
* Only message-creating calls are retried; a 429 on an edit or a draft means a
|
|
57
|
+
* skipped stream frame, not a lost message.
|
|
58
|
+
*/
|
|
59
|
+
function rateLimitRetryAfter(error) {
|
|
60
|
+
if (error?.providerCode !== 429 && error?.status !== 429 && error?.code !== 'telegram-429') {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
const seconds = Number(error?.retry_after);
|
|
64
|
+
return Number.isFinite(seconds) && seconds >= 0 ? seconds : 1;
|
|
65
|
+
}
|
|
66
|
+
|
|
29
67
|
function preserveProviderMetadata(target, source) {
|
|
30
68
|
if (source?.providerCode !== undefined) target.providerCode = source.providerCode;
|
|
31
69
|
if (source?.retry_after !== undefined) {
|
|
@@ -152,6 +190,12 @@ export class TelegramApi {
|
|
|
152
190
|
#FormDataImpl;
|
|
153
191
|
#baseUrl;
|
|
154
192
|
#fileUploadTimeoutMs;
|
|
193
|
+
#sendLimit;
|
|
194
|
+
#logger;
|
|
195
|
+
// Per chat: timestamps of the messages this bot created in the last window.
|
|
196
|
+
#sendTimestamps = new Map();
|
|
197
|
+
// Per chat: tail of the send queue, so parallel callers share one budget.
|
|
198
|
+
#sendQueue = new Map();
|
|
155
199
|
|
|
156
200
|
constructor({
|
|
157
201
|
token,
|
|
@@ -159,6 +203,8 @@ export class TelegramApi {
|
|
|
159
203
|
FormDataImpl = globalThis.FormData,
|
|
160
204
|
baseUrl = DEFAULT_BASE_URL,
|
|
161
205
|
fileUploadTimeoutMs = DEFAULT_FILE_UPLOAD_TIMEOUT_MS,
|
|
206
|
+
sendLimitPerMinute = DEFAULT_SEND_LIMIT_PER_MINUTE,
|
|
207
|
+
logger = null,
|
|
162
208
|
}) {
|
|
163
209
|
if (!validTelegramToken(token)) throw new TypeError('Telegram Bot Token is invalid');
|
|
164
210
|
if (typeof fetchImpl !== 'function') throw new TypeError('TelegramApi requires fetch');
|
|
@@ -168,6 +214,10 @@ export class TelegramApi {
|
|
|
168
214
|
this.#FormDataImpl = FormDataImpl;
|
|
169
215
|
this.#baseUrl = new URL(baseUrl);
|
|
170
216
|
this.#fileUploadTimeoutMs = positiveTimeout(fileUploadTimeoutMs, 'fileUploadTimeoutMs');
|
|
217
|
+
this.#sendLimit = Number.isInteger(sendLimitPerMinute) && sendLimitPerMinute >= 1
|
|
218
|
+
? sendLimitPerMinute
|
|
219
|
+
: DEFAULT_SEND_LIMIT_PER_MINUTE;
|
|
220
|
+
this.#logger = logger;
|
|
171
221
|
}
|
|
172
222
|
|
|
173
223
|
async getMe(options = {}) {
|
|
@@ -178,6 +228,18 @@ export class TelegramApi {
|
|
|
178
228
|
return this.#call('getWebhookInfo', {}, options);
|
|
179
229
|
}
|
|
180
230
|
|
|
231
|
+
/**
|
|
232
|
+
* Look a chat up by numeric id, `@username` or an invite link.
|
|
233
|
+
*
|
|
234
|
+
* The settings page uses this to turn a pasted group reference into a chat
|
|
235
|
+
* id; the bot must already be able to see the chat for the lookup to work.
|
|
236
|
+
*/
|
|
237
|
+
async getChat({ chatId, signal } = {}) {
|
|
238
|
+
const id = cleanString(chatId);
|
|
239
|
+
if (!id || id.length > 512) throw new TypeError('Telegram chat id is invalid');
|
|
240
|
+
return this.#call('getChat', { chat_id: id }, { signal });
|
|
241
|
+
}
|
|
242
|
+
|
|
181
243
|
async getUpdates({ offset, timeout = 25, signal } = {}) {
|
|
182
244
|
const payload = {
|
|
183
245
|
timeout,
|
|
@@ -240,7 +302,7 @@ export class TelegramApi {
|
|
|
240
302
|
}
|
|
241
303
|
|
|
242
304
|
async sendMessage({ chatId, text, replyToMessageId, messageThreadId, replyMarkup, signal }) {
|
|
243
|
-
return this.#
|
|
305
|
+
return this.#sendMessageCall('sendMessage', {
|
|
244
306
|
chat_id: chatId,
|
|
245
307
|
text,
|
|
246
308
|
link_preview_options: { is_disabled: true },
|
|
@@ -268,7 +330,7 @@ export class TelegramApi {
|
|
|
268
330
|
if (!Number.isSafeInteger(messageId)) {
|
|
269
331
|
throw new TypeError('Telegram message id must be a safe integer');
|
|
270
332
|
}
|
|
271
|
-
return this.#
|
|
333
|
+
return this.#callUnbudgeted('editMessageReplyMarkup', {
|
|
272
334
|
chat_id: chatId,
|
|
273
335
|
message_id: messageId,
|
|
274
336
|
...(replyMarkup === undefined ? {} : { reply_markup: inputReplyMarkup(replyMarkup) }),
|
|
@@ -291,7 +353,7 @@ export class TelegramApi {
|
|
|
291
353
|
messageThreadId,
|
|
292
354
|
signal,
|
|
293
355
|
}) {
|
|
294
|
-
return this.#
|
|
356
|
+
return this.#sendMessageCall('sendRichMessage', {
|
|
295
357
|
chat_id: chatId,
|
|
296
358
|
rich_message: inputRichMessage(richMessage),
|
|
297
359
|
...(replyToMessageId ? {
|
|
@@ -305,7 +367,7 @@ export class TelegramApi {
|
|
|
305
367
|
if (!Number.isSafeInteger(draftId) || draftId === 0) {
|
|
306
368
|
throw new TypeError('Telegram rich message draft id must be a non-zero integer');
|
|
307
369
|
}
|
|
308
|
-
return this.#
|
|
370
|
+
return this.#callUnbudgeted('sendRichMessageDraft', {
|
|
309
371
|
chat_id: chatId,
|
|
310
372
|
draft_id: draftId,
|
|
311
373
|
rich_message: inputRichMessage(richMessage),
|
|
@@ -345,45 +407,165 @@ export class TelegramApi {
|
|
|
345
407
|
|| !Buffer.isBuffer(file.bytes)) {
|
|
346
408
|
throw new TypeError(`A Telegram ${mediaLabel} is required`);
|
|
347
409
|
}
|
|
348
|
-
const payload = new this.#FormDataImpl();
|
|
349
|
-
payload.append('chat_id', String(chatId));
|
|
350
|
-
payload.append(
|
|
351
|
-
fieldName,
|
|
352
|
-
new Blob([file.bytes], { type: file.mediaType ?? 'application/octet-stream' }),
|
|
353
|
-
file.fileName,
|
|
354
|
-
);
|
|
355
|
-
if (replyToMessageId) {
|
|
356
|
-
payload.append('reply_parameters', JSON.stringify({
|
|
357
|
-
message_id: replyToMessageId,
|
|
358
|
-
allow_sending_without_reply: true,
|
|
359
|
-
}));
|
|
360
|
-
}
|
|
361
|
-
if (messageThreadId) payload.append('message_thread_id', String(messageThreadId));
|
|
362
410
|
if (signal?.aborted) throw abortReason(signal);
|
|
363
|
-
|
|
411
|
+
// A multipart body can be consumed only once, so every attempt rebuilds it.
|
|
412
|
+
const dispatch = async () => {
|
|
413
|
+
// The upload timeout starts here, not when the caller asked for the send:
|
|
414
|
+
// a file queued behind the chat's send budget (or behind a 429 retry)
|
|
415
|
+
// would otherwise expire before its first request even opens, and the
|
|
416
|
+
// file would be reported as uncertain although nothing was sent.
|
|
417
|
+
const uploadSignal = requestSignal(signal, this.#fileUploadTimeoutMs);
|
|
418
|
+
const payload = new this.#FormDataImpl();
|
|
419
|
+
payload.append('chat_id', String(chatId));
|
|
420
|
+
payload.append(
|
|
421
|
+
fieldName,
|
|
422
|
+
new Blob([file.bytes], { type: file.mediaType ?? 'application/octet-stream' }),
|
|
423
|
+
file.fileName,
|
|
424
|
+
);
|
|
425
|
+
if (replyToMessageId) {
|
|
426
|
+
payload.append('reply_parameters', JSON.stringify({
|
|
427
|
+
message_id: replyToMessageId,
|
|
428
|
+
allow_sending_without_reply: true,
|
|
429
|
+
}));
|
|
430
|
+
}
|
|
431
|
+
if (messageThreadId) payload.append('message_thread_id', String(messageThreadId));
|
|
432
|
+
try {
|
|
433
|
+
return await this.#call(method, payload, {
|
|
434
|
+
signal: uploadSignal,
|
|
435
|
+
timeoutMs: this.#fileUploadTimeoutMs,
|
|
436
|
+
multipart: true,
|
|
437
|
+
});
|
|
438
|
+
} catch (error) {
|
|
439
|
+
if (signal?.aborted) throw abortReason(signal);
|
|
440
|
+
if (error?.deliveryOutcome === 'unknown') {
|
|
441
|
+
throw uncertainTelegramDelivery(error?.cause ?? error, mediaLabel);
|
|
442
|
+
}
|
|
443
|
+
if (error?.code?.startsWith?.('telegram-')) {
|
|
444
|
+
throw telegramArtifactProviderError(error, mediaLabel);
|
|
445
|
+
}
|
|
446
|
+
throw uncertainTelegramDelivery(error, mediaLabel);
|
|
447
|
+
}
|
|
448
|
+
};
|
|
449
|
+
return this.#sendMessageCall(method, { chat_id: chatId }, { signal }, dispatch);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* Run a message-creating call inside the chat's send budget and retry it
|
|
454
|
+
* while Telegram answers 429.
|
|
455
|
+
*
|
|
456
|
+
* Only these calls are budgeted: Telegram charges its per-chat limit for new
|
|
457
|
+
* messages, while edits, drafts, typing actions, reactions and callback
|
|
458
|
+
* acknowledgements are free and must stay responsive during a burst.
|
|
459
|
+
*/
|
|
460
|
+
async #sendMessageCall(method, payload, options, dispatch = null) {
|
|
461
|
+
const { signal } = options;
|
|
462
|
+
const chatId = String(payload.chat_id ?? '');
|
|
463
|
+
await this.#reserveSendSlot(method, chatId, signal);
|
|
464
|
+
let waitedMs = 0;
|
|
465
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
466
|
+
try {
|
|
467
|
+
return await (dispatch ?? (() => this.#call(method, payload, options)))();
|
|
468
|
+
} catch (error) {
|
|
469
|
+
const retryAfter = rateLimitRetryAfter(error);
|
|
470
|
+
if (retryAfter === null) throw error;
|
|
471
|
+
const delayMs = Math.ceil(retryAfter * 1000);
|
|
472
|
+
if (attempt >= MAX_SEND_ATTEMPTS || waitedMs + delayMs > MAX_RATE_LIMIT_WAIT_MS) {
|
|
473
|
+
const limited = preserveProviderMetadata(new Error(
|
|
474
|
+
`Telegram ${method} is rate limited in chat ${chatId}`,
|
|
475
|
+
{ cause: error },
|
|
476
|
+
), error);
|
|
477
|
+
limited.code = 'channel-rate-limit';
|
|
478
|
+
// The caller still has to tell the user when the chat frees up.
|
|
479
|
+
limited.retry_after = retryAfter;
|
|
480
|
+
limited.retryAfter = retryAfter;
|
|
481
|
+
throw limited;
|
|
482
|
+
}
|
|
483
|
+
waitedMs += delayMs;
|
|
484
|
+
this.#log(
|
|
485
|
+
`[dsh-im:telegram] chat ${chatId} ${method} rate limited by Telegram,`
|
|
486
|
+
+ ` retrying in ${delayMs} ms (attempt ${attempt + 1} of ${MAX_SEND_ATTEMPTS})`,
|
|
487
|
+
);
|
|
488
|
+
await waitForDelay(delayMs, signal);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* Wait until this chat has a free slot in its budget.
|
|
495
|
+
*
|
|
496
|
+
* The budget belongs to the chat, not to the bot, so one busy group cannot
|
|
497
|
+
* starve the others. Waiting beats dropping: the caller's message is what the
|
|
498
|
+
* user asked for, and a slot always comes free within the window.
|
|
499
|
+
*/
|
|
500
|
+
async #reserveSendSlot(method, chatId, signal) {
|
|
501
|
+
// Parallel callers to the same chat must queue up, otherwise they would all
|
|
502
|
+
// read the same free budget and overshoot the limit together.
|
|
503
|
+
const previous = this.#sendQueue.get(chatId) ?? Promise.resolve();
|
|
504
|
+
let release = () => {};
|
|
505
|
+
const gate = new Promise((resolve) => { release = resolve; });
|
|
506
|
+
const tail = previous.then(() => gate);
|
|
507
|
+
this.#sendQueue.set(chatId, tail);
|
|
508
|
+
await previous;
|
|
364
509
|
try {
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
510
|
+
await this.#waitForSendBudget(method, chatId, signal);
|
|
511
|
+
} finally {
|
|
512
|
+
release();
|
|
513
|
+
if (this.#sendQueue.get(chatId) === tail) this.#sendQueue.delete(chatId);
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
async #waitForSendBudget(method, chatId, signal) {
|
|
518
|
+
for (;;) {
|
|
371
519
|
if (signal?.aborted) throw abortReason(signal);
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
if (
|
|
376
|
-
|
|
520
|
+
const now = Date.now();
|
|
521
|
+
const recent = (this.#sendTimestamps.get(chatId) ?? [])
|
|
522
|
+
.filter((at) => now - at < SEND_WINDOW_MS);
|
|
523
|
+
if (recent.length < this.#sendLimit) {
|
|
524
|
+
recent.push(now);
|
|
525
|
+
this.#sendTimestamps.set(chatId, recent);
|
|
526
|
+
return;
|
|
377
527
|
}
|
|
378
|
-
|
|
528
|
+
const delayMs = SEND_WINDOW_MS - (now - recent[0]);
|
|
529
|
+
this.#sendTimestamps.set(chatId, recent);
|
|
530
|
+
this.#log(
|
|
531
|
+
`[dsh-im:telegram] chat ${chatId} ${method} waits ${delayMs} ms`
|
|
532
|
+
+ ` for the next send slot (limit ${this.#sendLimit} per minute)`,
|
|
533
|
+
);
|
|
534
|
+
await waitForDelay(delayMs, signal);
|
|
379
535
|
}
|
|
380
536
|
}
|
|
381
537
|
|
|
538
|
+
/**
|
|
539
|
+
* Call a method that Telegram does not charge against the send budget.
|
|
540
|
+
*
|
|
541
|
+
* A 429 here is not retried: the frame it carries is already superseded by the
|
|
542
|
+
* next one, and waiting would stall the stream. It resolves to `undefined`
|
|
543
|
+
* instead of rejecting, because a rejected edit has nobody waiting for it and
|
|
544
|
+
* would surface as an unhandled rejection; a caller that needs the edit to be
|
|
545
|
+
* on screen checks for `undefined` and falls back.
|
|
546
|
+
*/
|
|
547
|
+
async #callUnbudgeted(method, payload, options = {}) {
|
|
548
|
+
try {
|
|
549
|
+
return await this.#call(method, payload, options);
|
|
550
|
+
} catch (error) {
|
|
551
|
+
if (rateLimitRetryAfter(error) === null) throw error;
|
|
552
|
+
this.#log(
|
|
553
|
+
`[dsh-im:telegram] chat ${String(payload.chat_id ?? '')} ${method}`
|
|
554
|
+
+ ' rate limited; skipping this update',
|
|
555
|
+
);
|
|
556
|
+
return undefined;
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
#log(message) {
|
|
561
|
+
this.#logger?.warn?.(message);
|
|
562
|
+
}
|
|
563
|
+
|
|
382
564
|
async editMessageText({ chatId, messageId, text, richMessage, signal }) {
|
|
383
565
|
if ((text === undefined) === (richMessage === undefined)) {
|
|
384
566
|
throw new TypeError('Telegram message edit requires exactly one of text or richMessage');
|
|
385
567
|
}
|
|
386
|
-
return this.#
|
|
568
|
+
return this.#callUnbudgeted('editMessageText', {
|
|
387
569
|
chat_id: chatId,
|
|
388
570
|
message_id: messageId,
|
|
389
571
|
...(text === undefined ? { rich_message: inputRichMessage(richMessage) } : {
|
|
@@ -393,6 +575,15 @@ export class TelegramApi {
|
|
|
393
575
|
}, { signal });
|
|
394
576
|
}
|
|
395
577
|
|
|
578
|
+
/** Telegram notifies on new messages only, never on edits, so dropping the
|
|
579
|
+
* progress placeholder takes a delete rather than a rewrite. */
|
|
580
|
+
async deleteMessage({ chatId, messageId, signal }) {
|
|
581
|
+
return this.#call('deleteMessage', {
|
|
582
|
+
chat_id: chatId,
|
|
583
|
+
message_id: messageId,
|
|
584
|
+
}, { signal });
|
|
585
|
+
}
|
|
586
|
+
|
|
396
587
|
async sendChatAction({ chatId, messageThreadId, signal }) {
|
|
397
588
|
return this.#call('sendChatAction', {
|
|
398
589
|
chat_id: chatId,
|
|
@@ -5,7 +5,10 @@ export const TELEGRAM_DESCRIPTOR = Object.freeze({
|
|
|
5
5
|
key: 'telegram',
|
|
6
6
|
label: 'Telegram',
|
|
7
7
|
connectionLabel: ' Bot API 长轮询',
|
|
8
|
-
|
|
8
|
+
// A finished turn leaves no reaction behind: Telegram keeps offering reaction
|
|
9
|
+
// controls on a message that carries one, which repeats for the reader even
|
|
10
|
+
// with reaction notifications off. A failure still keeps its mark.
|
|
11
|
+
reactions: Object.freeze({ processing: '👀', success: null, error: '👎' }),
|
|
9
12
|
});
|
|
10
13
|
|
|
11
14
|
/** One keyboard row per option; beyond this the list stops being scannable. */
|
|
@@ -2,14 +2,35 @@ import { TokenBotController } from '../shared/token-bot-controller.mjs';
|
|
|
2
2
|
import {
|
|
3
3
|
deriveTelegramBotIdentity,
|
|
4
4
|
maskTelegramBotId,
|
|
5
|
+
normalizeSendLimitPerMinute,
|
|
5
6
|
normalizeTelegramAccessPolicy,
|
|
6
7
|
} from './config-store.mjs';
|
|
7
|
-
import {
|
|
8
|
+
import {
|
|
9
|
+
normalizeThinkingIntervalSeconds,
|
|
10
|
+
normalizeThinkingNumbering,
|
|
11
|
+
} from '../shared/thinking-cadence.mjs';
|
|
12
|
+
import {
|
|
13
|
+
GROUP_TRIGGER_VERSION,
|
|
14
|
+
groupTriggersSettings,
|
|
15
|
+
normalizeGroupTriggers,
|
|
16
|
+
parseGroupReference,
|
|
17
|
+
resolveGroupReference,
|
|
18
|
+
} from './group-triggers.mjs';
|
|
19
|
+
import { inspectTelegramToken, TelegramApi } from './telegram-api.mjs';
|
|
20
|
+
import { createTelegramHttpTransport } from './telegram-http.mjs';
|
|
8
21
|
import { TELEGRAM_DESCRIPTOR } from './telegram-bridge.mjs';
|
|
9
22
|
|
|
10
23
|
export class TelegramController extends TokenBotController {
|
|
11
24
|
#configStore;
|
|
12
25
|
|
|
26
|
+
#credentials;
|
|
27
|
+
|
|
28
|
+
#groupHistory;
|
|
29
|
+
|
|
30
|
+
#createApi;
|
|
31
|
+
|
|
32
|
+
#createHttpTransport;
|
|
33
|
+
|
|
13
34
|
constructor(options) {
|
|
14
35
|
super({
|
|
15
36
|
...options,
|
|
@@ -19,6 +40,11 @@ export class TelegramController extends TokenBotController {
|
|
|
19
40
|
maskPlatformId: maskTelegramBotId,
|
|
20
41
|
});
|
|
21
42
|
this.#configStore = options.configStore;
|
|
43
|
+
this.#credentials = options.credentials ?? null;
|
|
44
|
+
this.#groupHistory = options.groupHistory ?? null;
|
|
45
|
+
this.#createApi = options.createApi ?? ((apiOptions) => new TelegramApi(apiOptions));
|
|
46
|
+
// Lookup must go through the same proxy-aware transport as the runtime.
|
|
47
|
+
this.#createHttpTransport = options.createHttpTransport ?? createTelegramHttpTransport;
|
|
22
48
|
}
|
|
23
49
|
|
|
24
50
|
status() {
|
|
@@ -33,6 +59,11 @@ export class TelegramController extends TokenBotController {
|
|
|
33
59
|
accessPolicy,
|
|
34
60
|
// Default ON; only an explicit false in the config opts out.
|
|
35
61
|
thinkingTraces: config?.thinkingTraces !== false,
|
|
62
|
+
thinkingNumbering: normalizeThinkingNumbering(config?.thinkingNumbering),
|
|
63
|
+
// 0 means no pacing, which is also what an absent field means.
|
|
64
|
+
thinkingIntervalSeconds: normalizeThinkingIntervalSeconds(config?.thinkingIntervalSeconds),
|
|
65
|
+
groupTriggers: normalizeGroupTriggers(config?.groupTriggers),
|
|
66
|
+
sendLimitPerMinute: normalizeSendLimitPerMinute(config?.sendLimitPerMinute),
|
|
36
67
|
};
|
|
37
68
|
}),
|
|
38
69
|
};
|
|
@@ -49,4 +80,111 @@ export class TelegramController extends TokenBotController {
|
|
|
49
80
|
thinkingTraces: value === true,
|
|
50
81
|
}));
|
|
51
82
|
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Persist trace numbering and pacing; the runtime restarts with the new
|
|
86
|
+
* values, so the next turn already follows them.
|
|
87
|
+
*/
|
|
88
|
+
async setThinkingCadence(botId, { thinkingNumbering, thinkingIntervalSeconds } = {}) {
|
|
89
|
+
const numbering = normalizeThinkingNumbering(thinkingNumbering);
|
|
90
|
+
const interval = normalizeThinkingIntervalSeconds(thinkingIntervalSeconds);
|
|
91
|
+
return this.updateBotConfig(botId, (config) => ({
|
|
92
|
+
...config,
|
|
93
|
+
thinkingNumbering: numbering,
|
|
94
|
+
thinkingIntervalSeconds: interval,
|
|
95
|
+
}));
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Persist the per-chat send limit; the runtime restarts with the new value. */
|
|
99
|
+
async setSendLimitPerMinute(botId, value) {
|
|
100
|
+
const sendLimitPerMinute = normalizeSendLimitPerMinute(value);
|
|
101
|
+
return this.updateBotConfig(botId, (config) => ({ ...config, sendLimitPerMinute }));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Channels the bot has actually received messages from. */
|
|
105
|
+
async knownGroups() {
|
|
106
|
+
if (typeof this.#groupHistory?.listGroups !== 'function') return [];
|
|
107
|
+
try {
|
|
108
|
+
return await this.#groupHistory.listGroups({ channel: 'telegram' });
|
|
109
|
+
} catch {
|
|
110
|
+
// History only feeds the settings panel: a broken archive must not take
|
|
111
|
+
// the settings page down with it.
|
|
112
|
+
return [];
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async groupTriggersPanel(botId) {
|
|
117
|
+
const config = this.#configStore.get(botId);
|
|
118
|
+
if (!config) throw new Error('Unknown Telegram bot');
|
|
119
|
+
return groupTriggersSettings(config.groupTriggers, await this.knownGroups());
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Persist the per-group reply rules.
|
|
124
|
+
*
|
|
125
|
+
* `removed` lists the chats the owner deleted in the panel: they keep their
|
|
126
|
+
* archived history but stop being offered in the settings page.
|
|
127
|
+
*/
|
|
128
|
+
async updateGroupTriggers(botId, { config: value, removed = [] } = {}) {
|
|
129
|
+
const stored = this.#configStore.get(botId);
|
|
130
|
+
if (!stored) throw new Error('Unknown Telegram bot');
|
|
131
|
+
const normalized = normalizeGroupTriggers(value);
|
|
132
|
+
const groups = { ...normalized.groups };
|
|
133
|
+
// The panel never echoes `hiddenGroupIds`, so they are merged with what the
|
|
134
|
+
// store already holds; otherwise a second save would resurrect every group
|
|
135
|
+
// removed by the first one.
|
|
136
|
+
const hidden = new Set(normalizeGroupTriggers(stored.groupTriggers).hiddenGroupIds);
|
|
137
|
+
for (const chatId of Array.isArray(removed) ? removed : []) {
|
|
138
|
+
const id = typeof chatId === 'string' ? chatId.trim() : '';
|
|
139
|
+
if (!id) continue;
|
|
140
|
+
delete groups[id];
|
|
141
|
+
hidden.add(id);
|
|
142
|
+
}
|
|
143
|
+
// An explicit rule means the owner brought the chat back into the panel.
|
|
144
|
+
for (const chatId of Object.keys(groups)) hidden.delete(chatId);
|
|
145
|
+
const next = {
|
|
146
|
+
version: GROUP_TRIGGER_VERSION,
|
|
147
|
+
defaults: normalized.defaults,
|
|
148
|
+
groups,
|
|
149
|
+
hiddenGroupIds: [...hidden],
|
|
150
|
+
};
|
|
151
|
+
await this.updateBotConfig(botId, (config) => ({ ...config, groupTriggers: next }));
|
|
152
|
+
return groupTriggersSettings(next, await this.knownGroups());
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Turn a pasted group reference into a chat id.
|
|
157
|
+
*
|
|
158
|
+
* Numeric IDs resolve locally; usernames and invite links need the Bot API,
|
|
159
|
+
* so the call borrows the bot's own token instead of asking the owner for it.
|
|
160
|
+
*/
|
|
161
|
+
async resolveGroupTrigger(botId, input) {
|
|
162
|
+
const config = this.#configStore.get(botId);
|
|
163
|
+
if (!config) throw new Error('Unknown Telegram bot');
|
|
164
|
+
let token = '';
|
|
165
|
+
if (this.#credentials && typeof this.#credentials.resolve === 'function') {
|
|
166
|
+
const resolved = await this.#credentials.resolve(config.tokenRef);
|
|
167
|
+
token = typeof resolved?.value === 'string' ? resolved.value.trim() : '';
|
|
168
|
+
}
|
|
169
|
+
// Numeric ids and message links resolve offline; only a username or an
|
|
170
|
+
// invite link needs the Bot API (and therefore a transport).
|
|
171
|
+
const reference = parseGroupReference(input);
|
|
172
|
+
if (reference.chatId) {
|
|
173
|
+
return Object.freeze({ chatId: reference.chatId, title: null, type: null, verified: false });
|
|
174
|
+
}
|
|
175
|
+
if (!token) return resolveGroupReference(input, {});
|
|
176
|
+
const transport = this.#createHttpTransport();
|
|
177
|
+
try {
|
|
178
|
+
const api = this.#createApi({
|
|
179
|
+
token,
|
|
180
|
+
fetchImpl: transport.fetchImpl,
|
|
181
|
+
FormDataImpl: transport.FormDataImpl,
|
|
182
|
+
});
|
|
183
|
+
return await resolveGroupReference(input, {
|
|
184
|
+
getChat: (chatId) => api.getChat({ chatId }),
|
|
185
|
+
});
|
|
186
|
+
} finally {
|
|
187
|
+
await transport.destroy?.();
|
|
188
|
+
}
|
|
189
|
+
}
|
|
52
190
|
}
|