@xmanrui/dsh-im 5.4.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/lib/client.js +2293 -444
- package/lib/index.js +402 -335
- 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/styles.js +4 -0
- package/plugin-src/client/channels/telegram/thinking-traces.js +138 -5
- package/plugin-src/client/delivery-settings.js +2 -2
- package/plugin-src/client/i18n-ru.js +1615 -0
- package/plugin-src/client/i18n.js +71 -0
- package/plugin-src/client/index.js +8 -1
- package/plugin-src/host/channels/shared/production.mjs +5 -0
- 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/telegram/production.mjs +7 -0
- package/plugin-src/host/delivery-adapter.mjs +41 -33
- package/plugin-src/host/delivery-service.mjs +42 -0
- package/plugin-src/host/ds-bot-client.mjs +31 -18
- package/plugin-src/host/ds-bot-question-sync.mjs +78 -0
- package/plugin-src/host/index.mjs +3 -0
- 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-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/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/harness-client.mjs +5 -4
- package/src/channels/shared/history-command.mjs +2 -1
- 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-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-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/telegram/config-store.mjs +34 -1
- package/src/channels/telegram/telegram-api.mjs +211 -32
- package/src/channels/telegram/telegram-bridge.mjs +4 -1
- package/src/channels/telegram/telegram-controller.mjs +29 -0
- package/src/channels/telegram/telegram-runtime.mjs +507 -176
- package/src/channels/telegram/voice.mjs +250 -0
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isSessionNotFound } from './session-error.mjs';
|
|
1
2
|
import { createCommandListSnapshots } from './command-list-snapshots.mjs';
|
|
2
3
|
import { t } from './i18n.mjs';
|
|
3
4
|
import { withSessionBindingLock } from './session-binding-lock.mjs';
|
|
@@ -50,7 +51,7 @@ function errorMessage(error, writing) {
|
|
|
50
51
|
if (code === WORKSPACE_SESSION_STALE || code === 'workspace-bot-not-found') {
|
|
51
52
|
return t('工作区或机器人状态已发生变化,请重试。');
|
|
52
53
|
}
|
|
53
|
-
if (
|
|
54
|
+
if (isSessionNotFound(code) || code === 'agent-not-found') {
|
|
54
55
|
return t('当前聊天绑定的会话已不存在,请先绑定或建立会话。');
|
|
55
56
|
}
|
|
56
57
|
if (['commands-unavailable', 'permissions-unavailable', 'harness-api-not-found',
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-chat send limit for Telegram.
|
|
3
|
+
*
|
|
4
|
+
* Telegram counts the messages a bot creates per chat and answers 429 once the
|
|
5
|
+
* budget for a chat is gone. The bot therefore paces its own new messages and
|
|
6
|
+
* waits for the next free slot instead of dropping them. The value lives in the
|
|
7
|
+
* bot config, is editable from the settings page, and is clamped on both sides:
|
|
8
|
+
* an unparseable form entry must never leave a bot unable to send.
|
|
9
|
+
*
|
|
10
|
+
* Kept free of Node imports so the Web client can share the same rules.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export const SET_SEND_LIMIT_ENDPOINT = 'bot.send-limit.set';
|
|
14
|
+
export const DEFAULT_SEND_LIMIT_PER_MINUTE = 15;
|
|
15
|
+
export const SEND_LIMIT_MIN_PER_MINUTE = 1;
|
|
16
|
+
/** Above this the bot would only wait for a budget Telegram never grants. */
|
|
17
|
+
export const SEND_LIMIT_MAX_PER_MINUTE = 30;
|
|
18
|
+
|
|
19
|
+
function clampSendLimit(value) {
|
|
20
|
+
return Math.min(
|
|
21
|
+
SEND_LIMIT_MAX_PER_MINUTE,
|
|
22
|
+
Math.max(SEND_LIMIT_MIN_PER_MINUTE, Math.round(value)),
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* A usable limit per minute: 1..30, default 15.
|
|
28
|
+
*
|
|
29
|
+
* Numeric strings from the form are accepted; anything else — missing, NaN,
|
|
30
|
+
* booleans, objects, garbage text — falls back to the default.
|
|
31
|
+
*/
|
|
32
|
+
export function normalizeSendLimitPerMinute(value) {
|
|
33
|
+
const numeric = typeof value === 'string' && value.trim() ? Number(value.trim()) : value;
|
|
34
|
+
if (typeof numeric !== 'number' || !Number.isFinite(numeric)) {
|
|
35
|
+
return DEFAULT_SEND_LIMIT_PER_MINUTE;
|
|
36
|
+
}
|
|
37
|
+
return clampSendLimit(numeric);
|
|
38
|
+
}
|
|
@@ -66,6 +66,8 @@ export function beginStatusReaction({
|
|
|
66
66
|
}
|
|
67
67
|
};
|
|
68
68
|
|
|
69
|
+
// `emoji` may be null: the transition then only removes the previous
|
|
70
|
+
// reaction, which is how a channel asks for a clean message at the end.
|
|
69
71
|
const transition = async (emoji) => {
|
|
70
72
|
if (currentReaction !== null) {
|
|
71
73
|
const previous = currentReaction;
|
|
@@ -1308,6 +1308,10 @@ export class TextHarnessBridge {
|
|
|
1308
1308
|
return;
|
|
1309
1309
|
}
|
|
1310
1310
|
if (update.type === 'reasoning') return;
|
|
1311
|
+
// A carrier that delivers the answer as its own message must not
|
|
1312
|
+
// stream that answer into itself first: the reader would see the
|
|
1313
|
+
// reply twice, and every preview costs an edit.
|
|
1314
|
+
if (update.type === 'text' && stream.previewAnswer === false) return;
|
|
1311
1315
|
const progress = update.type === 'text' ? update.text
|
|
1312
1316
|
: update.type === 'tool' ? t('正在使用{name}…', { name: update.name }) : update.text;
|
|
1313
1317
|
if (progress) {
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pacing and numbering for Telegram "thinking trace" frames.
|
|
3
|
+
*
|
|
4
|
+
* A busy turn emits dozens of 💭/🔧 messages, so the owner can pace them to at
|
|
5
|
+
* most one frame per N seconds and prefix each frame with its number in the
|
|
6
|
+
* turn. Both values live in the bot config and are clamped here, once, so a
|
|
7
|
+
* half-typed form entry can never reach the runtime.
|
|
8
|
+
*
|
|
9
|
+
* Kept free of Node imports so the Web client can share the same rules.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export const SET_THINKING_CADENCE_ENDPOINT = 'bot.thinking-cadence.set';
|
|
13
|
+
/** 0 means "no pacing": every frame goes out as it arrives. */
|
|
14
|
+
export const DEFAULT_THINKING_INTERVAL_SECONDS = 0;
|
|
15
|
+
/** A longer window stops being a trace: the answer would overtake it. */
|
|
16
|
+
export const THINKING_INTERVAL_MAX_SECONDS = 60;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* A usable interval in whole seconds, 0..60.
|
|
20
|
+
*
|
|
21
|
+
* Numeric strings from the form are accepted; anything else — missing, NaN,
|
|
22
|
+
* booleans, objects, fractional or garbage text — becomes 0, because a wrong
|
|
23
|
+
* number must not silently slow the trace down.
|
|
24
|
+
*/
|
|
25
|
+
export function normalizeThinkingIntervalSeconds(value) {
|
|
26
|
+
const numeric = typeof value === 'string' && value.trim() ? Number(value.trim()) : value;
|
|
27
|
+
if (typeof numeric !== 'number' || !Number.isFinite(numeric) || !Number.isInteger(numeric)) {
|
|
28
|
+
return DEFAULT_THINKING_INTERVAL_SECONDS;
|
|
29
|
+
}
|
|
30
|
+
return Math.min(THINKING_INTERVAL_MAX_SECONDS, Math.max(0, numeric));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Numbering is off unless the config says otherwise. */
|
|
34
|
+
export function normalizeThinkingNumbering(value) {
|
|
35
|
+
return value === true;
|
|
36
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isSessionNotFound } from './session-error.mjs';
|
|
1
2
|
import { realpath, stat } from 'node:fs/promises';
|
|
2
3
|
import { isAbsolute, resolve } from 'node:path';
|
|
3
4
|
|
|
@@ -317,7 +318,7 @@ function sessionBindErrorMessage(error) {
|
|
|
317
318
|
return t(`Session ID 格式无效。
|
|
318
319
|
{usage}`, { usage: t(SESSION_BIND_USAGE) });
|
|
319
320
|
}
|
|
320
|
-
if (
|
|
321
|
+
if (error?.code === 'session-not-registered' || isSessionNotFound(error?.code)) {
|
|
321
322
|
return t('未找到该会话,请先执行 /sessionlist 确认 Session ID。');
|
|
322
323
|
}
|
|
323
324
|
if (error?.code === 'session-subagent-unsupported') {
|
|
@@ -5,6 +5,27 @@ import {
|
|
|
5
5
|
TokenBotConfigStore,
|
|
6
6
|
} from '../shared/token-config-store.mjs';
|
|
7
7
|
import { normalizeGroupTriggers } from './group-triggers.mjs';
|
|
8
|
+
import {
|
|
9
|
+
normalizeThinkingIntervalSeconds,
|
|
10
|
+
normalizeThinkingNumbering,
|
|
11
|
+
} from '../shared/thinking-cadence.mjs';
|
|
12
|
+
|
|
13
|
+
export {
|
|
14
|
+
DEFAULT_THINKING_INTERVAL_SECONDS,
|
|
15
|
+
normalizeThinkingIntervalSeconds,
|
|
16
|
+
normalizeThinkingNumbering,
|
|
17
|
+
SET_THINKING_CADENCE_ENDPOINT,
|
|
18
|
+
THINKING_INTERVAL_MAX_SECONDS,
|
|
19
|
+
} from '../shared/thinking-cadence.mjs';
|
|
20
|
+
import { normalizeSendLimitPerMinute } from '../shared/send-limit.mjs';
|
|
21
|
+
|
|
22
|
+
export {
|
|
23
|
+
DEFAULT_SEND_LIMIT_PER_MINUTE,
|
|
24
|
+
normalizeSendLimitPerMinute,
|
|
25
|
+
SEND_LIMIT_MAX_PER_MINUTE,
|
|
26
|
+
SEND_LIMIT_MIN_PER_MINUTE,
|
|
27
|
+
SET_SEND_LIMIT_ENDPOINT,
|
|
28
|
+
} from '../shared/send-limit.mjs';
|
|
8
29
|
|
|
9
30
|
const IDENTITY_OPTIONS = Object.freeze({
|
|
10
31
|
botPrefix: 'telegram',
|
|
@@ -53,7 +74,11 @@ function normalizeTelegramBotExtension(value) {
|
|
|
53
74
|
const hasAllowedUsers = Object.hasOwn(value, 'allowedUsers');
|
|
54
75
|
const hasThinkingTraces = Object.hasOwn(value, 'thinkingTraces');
|
|
55
76
|
const hasGroupTriggers = Object.hasOwn(value, 'groupTriggers');
|
|
56
|
-
|
|
77
|
+
const hasThinkingNumbering = Object.hasOwn(value, 'thinkingNumbering');
|
|
78
|
+
const hasThinkingInterval = Object.hasOwn(value, 'thinkingIntervalSeconds');
|
|
79
|
+
const hasSendLimit = Object.hasOwn(value, 'sendLimitPerMinute');
|
|
80
|
+
if (!hasAccessMode && !hasAllowedUsers && !hasThinkingTraces && !hasGroupTriggers
|
|
81
|
+
&& !hasThinkingNumbering && !hasThinkingInterval && !hasSendLimit) return {};
|
|
57
82
|
try {
|
|
58
83
|
const policy = normalizeTelegramAccessPolicy(value);
|
|
59
84
|
return {
|
|
@@ -63,6 +88,14 @@ function normalizeTelegramBotExtension(value) {
|
|
|
63
88
|
...(hasThinkingTraces ? { thinkingTraces: value.thinkingTraces === true } : {}),
|
|
64
89
|
// Per-group reply triggers; absent means "no rule configured".
|
|
65
90
|
...(hasGroupTriggers ? { groupTriggers: normalizeGroupTriggers(value.groupTriggers) } : {}),
|
|
91
|
+
// Trace cadence: stored clamped, so a bad value never reaches the runtime.
|
|
92
|
+
...(hasThinkingNumbering
|
|
93
|
+
? { thinkingNumbering: normalizeThinkingNumbering(value.thinkingNumbering) } : {}),
|
|
94
|
+
...(hasThinkingInterval
|
|
95
|
+
? { thinkingIntervalSeconds: normalizeThinkingIntervalSeconds(value.thinkingIntervalSeconds) }
|
|
96
|
+
: {}),
|
|
97
|
+
// Stored clamped so a bad value never reaches the runtime.
|
|
98
|
+
...(hasSendLimit ? { sendLimitPerMinute: normalizeSendLimitPerMinute(value.sendLimitPerMinute) } : {}),
|
|
66
99
|
};
|
|
67
100
|
} catch {
|
|
68
101
|
return null;
|
|
@@ -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 = {}) {
|
|
@@ -252,7 +302,7 @@ export class TelegramApi {
|
|
|
252
302
|
}
|
|
253
303
|
|
|
254
304
|
async sendMessage({ chatId, text, replyToMessageId, messageThreadId, replyMarkup, signal }) {
|
|
255
|
-
return this.#
|
|
305
|
+
return this.#sendMessageCall('sendMessage', {
|
|
256
306
|
chat_id: chatId,
|
|
257
307
|
text,
|
|
258
308
|
link_preview_options: { is_disabled: true },
|
|
@@ -280,7 +330,7 @@ export class TelegramApi {
|
|
|
280
330
|
if (!Number.isSafeInteger(messageId)) {
|
|
281
331
|
throw new TypeError('Telegram message id must be a safe integer');
|
|
282
332
|
}
|
|
283
|
-
return this.#
|
|
333
|
+
return this.#callUnbudgeted('editMessageReplyMarkup', {
|
|
284
334
|
chat_id: chatId,
|
|
285
335
|
message_id: messageId,
|
|
286
336
|
...(replyMarkup === undefined ? {} : { reply_markup: inputReplyMarkup(replyMarkup) }),
|
|
@@ -303,7 +353,7 @@ export class TelegramApi {
|
|
|
303
353
|
messageThreadId,
|
|
304
354
|
signal,
|
|
305
355
|
}) {
|
|
306
|
-
return this.#
|
|
356
|
+
return this.#sendMessageCall('sendRichMessage', {
|
|
307
357
|
chat_id: chatId,
|
|
308
358
|
rich_message: inputRichMessage(richMessage),
|
|
309
359
|
...(replyToMessageId ? {
|
|
@@ -317,7 +367,7 @@ export class TelegramApi {
|
|
|
317
367
|
if (!Number.isSafeInteger(draftId) || draftId === 0) {
|
|
318
368
|
throw new TypeError('Telegram rich message draft id must be a non-zero integer');
|
|
319
369
|
}
|
|
320
|
-
return this.#
|
|
370
|
+
return this.#callUnbudgeted('sendRichMessageDraft', {
|
|
321
371
|
chat_id: chatId,
|
|
322
372
|
draft_id: draftId,
|
|
323
373
|
rich_message: inputRichMessage(richMessage),
|
|
@@ -357,45 +407,165 @@ export class TelegramApi {
|
|
|
357
407
|
|| !Buffer.isBuffer(file.bytes)) {
|
|
358
408
|
throw new TypeError(`A Telegram ${mediaLabel} is required`);
|
|
359
409
|
}
|
|
360
|
-
const payload = new this.#FormDataImpl();
|
|
361
|
-
payload.append('chat_id', String(chatId));
|
|
362
|
-
payload.append(
|
|
363
|
-
fieldName,
|
|
364
|
-
new Blob([file.bytes], { type: file.mediaType ?? 'application/octet-stream' }),
|
|
365
|
-
file.fileName,
|
|
366
|
-
);
|
|
367
|
-
if (replyToMessageId) {
|
|
368
|
-
payload.append('reply_parameters', JSON.stringify({
|
|
369
|
-
message_id: replyToMessageId,
|
|
370
|
-
allow_sending_without_reply: true,
|
|
371
|
-
}));
|
|
372
|
-
}
|
|
373
|
-
if (messageThreadId) payload.append('message_thread_id', String(messageThreadId));
|
|
374
410
|
if (signal?.aborted) throw abortReason(signal);
|
|
375
|
-
|
|
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;
|
|
376
509
|
try {
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
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 (;;) {
|
|
383
519
|
if (signal?.aborted) throw abortReason(signal);
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
if (
|
|
388
|
-
|
|
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;
|
|
389
527
|
}
|
|
390
|
-
|
|
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);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
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;
|
|
391
557
|
}
|
|
392
558
|
}
|
|
393
559
|
|
|
560
|
+
#log(message) {
|
|
561
|
+
this.#logger?.warn?.(message);
|
|
562
|
+
}
|
|
563
|
+
|
|
394
564
|
async editMessageText({ chatId, messageId, text, richMessage, signal }) {
|
|
395
565
|
if ((text === undefined) === (richMessage === undefined)) {
|
|
396
566
|
throw new TypeError('Telegram message edit requires exactly one of text or richMessage');
|
|
397
567
|
}
|
|
398
|
-
return this.#
|
|
568
|
+
return this.#callUnbudgeted('editMessageText', {
|
|
399
569
|
chat_id: chatId,
|
|
400
570
|
message_id: messageId,
|
|
401
571
|
...(text === undefined ? { rich_message: inputRichMessage(richMessage) } : {
|
|
@@ -405,6 +575,15 @@ export class TelegramApi {
|
|
|
405
575
|
}, { signal });
|
|
406
576
|
}
|
|
407
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
|
+
|
|
408
587
|
async sendChatAction({ chatId, messageThreadId, signal }) {
|
|
409
588
|
return this.#call('sendChatAction', {
|
|
410
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,8 +2,13 @@ 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';
|
|
8
|
+
import {
|
|
9
|
+
normalizeThinkingIntervalSeconds,
|
|
10
|
+
normalizeThinkingNumbering,
|
|
11
|
+
} from '../shared/thinking-cadence.mjs';
|
|
7
12
|
import {
|
|
8
13
|
GROUP_TRIGGER_VERSION,
|
|
9
14
|
groupTriggersSettings,
|
|
@@ -54,7 +59,11 @@ export class TelegramController extends TokenBotController {
|
|
|
54
59
|
accessPolicy,
|
|
55
60
|
// Default ON; only an explicit false in the config opts out.
|
|
56
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),
|
|
57
65
|
groupTriggers: normalizeGroupTriggers(config?.groupTriggers),
|
|
66
|
+
sendLimitPerMinute: normalizeSendLimitPerMinute(config?.sendLimitPerMinute),
|
|
58
67
|
};
|
|
59
68
|
}),
|
|
60
69
|
};
|
|
@@ -72,6 +81,26 @@ export class TelegramController extends TokenBotController {
|
|
|
72
81
|
}));
|
|
73
82
|
}
|
|
74
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
|
+
|
|
75
104
|
/** Channels the bot has actually received messages from. */
|
|
76
105
|
async knownGroups() {
|
|
77
106
|
if (typeof this.#groupHistory?.listGroups !== 'function') return [];
|