@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
|
@@ -4,18 +4,25 @@ import { extractConnectionEvidence, createConnectionDiagnostics, atConnectionSta
|
|
|
4
4
|
import { createEditableMessageStream } from '../shared/editable-message-stream.mjs';
|
|
5
5
|
import { createTextDeliveryBlock } from '../shared/semantic/delivery.mjs';
|
|
6
6
|
import { t } from '../shared/i18n.mjs';
|
|
7
|
+
import { groupTriggerAddressed, normalizeGroupTriggers } from './group-triggers.mjs';
|
|
7
8
|
import { captureContextEnhancement } from '../shared/context-enhancement.mjs';
|
|
8
9
|
import { recoverAssistantTextByTimestamp } from '../shared/session-reply-recovery.mjs';
|
|
9
10
|
import { SHARED_COMMAND_CATALOG, commandsForChannel } from '../shared/command-catalog.mjs';
|
|
10
11
|
import { COMMANDS_MENU_BUTTON, TelegramApi, validateTelegramCommands } from './telegram-api.mjs';
|
|
11
12
|
import { createTelegramHttpTransport } from './telegram-http.mjs';
|
|
12
13
|
import { createTelegramBridgeStatus, TelegramHarnessBridge } from './telegram-bridge.mjs';
|
|
14
|
+
import { VOICE_MAX_BYTES, telegramVoiceSource, voiceFailureReason, voiceNote } from './voice.mjs';
|
|
15
|
+
import { evaluateInboundAccess } from '../shared/inbound-access.mjs';
|
|
16
|
+
import { createConversationQueue } from '../shared/conversation-queue.mjs';
|
|
13
17
|
import {
|
|
14
18
|
splitTelegramRegularText,
|
|
15
19
|
splitTelegramRichMarkdown,
|
|
16
20
|
toTelegramRichMarkdown,
|
|
17
21
|
} from './telegram-rich-message.mjs';
|
|
18
22
|
import {
|
|
23
|
+
normalizeThinkingIntervalSeconds,
|
|
24
|
+
normalizeThinkingNumbering,
|
|
25
|
+
normalizeSendLimitPerMinute,
|
|
19
26
|
TELEGRAM_ACCESS_MODES,
|
|
20
27
|
} from './config-store.mjs';
|
|
21
28
|
|
|
@@ -275,9 +282,74 @@ export function normalizeTelegramCallback(update, { botId } = {}) {
|
|
|
275
282
|
};
|
|
276
283
|
}
|
|
277
284
|
|
|
285
|
+
/**
|
|
286
|
+
* Access is decided before any download happens: a sender the allowlist refuses
|
|
287
|
+
* must not spend local CPU or a provider quota on a message that will be dropped.
|
|
288
|
+
*/
|
|
289
|
+
export function voiceMessageAllowed(accessPolicy, message) {
|
|
290
|
+
const decision = evaluateInboundAccess(accessPolicy, {
|
|
291
|
+
conversationType: message?.kind === 'direct' ? 'direct' : 'group',
|
|
292
|
+
senderIds: [message?.senderId],
|
|
293
|
+
text: '',
|
|
294
|
+
});
|
|
295
|
+
return decision.allowed === true;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function formatDurationMs(value) {
|
|
299
|
+
const ms = Math.max(1, Math.round(Number(value) || 0));
|
|
300
|
+
return ms < 1_000 ? `${ms}ms` : `${Math.round(ms / 1_000)}s`;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Fill `message.content` with a transcript or with an explicit note.
|
|
305
|
+
*
|
|
306
|
+
* `timeoutMs` bounds conversion plus provider time on its own controller, so a
|
|
307
|
+
* slow recognizer cannot hold the chat open for the runtime's lifetime.
|
|
308
|
+
*/
|
|
309
|
+
export async function fillVoiceContent({
|
|
310
|
+
message,
|
|
311
|
+
voice = message?.voice,
|
|
312
|
+
api,
|
|
313
|
+
transcriber,
|
|
314
|
+
timeoutMs = 60_000,
|
|
315
|
+
signal,
|
|
316
|
+
logFailure = null,
|
|
317
|
+
} = {}) {
|
|
318
|
+
if (!transcriber) {
|
|
319
|
+
message.content = voiceNote({ voice, reason: 'speech recognition is not enabled in this Host' });
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
const controller = new AbortController();
|
|
323
|
+
const onAbort = () => controller.abort();
|
|
324
|
+
const timer = setTimeout(() => controller.abort(), Math.max(1, timeoutMs));
|
|
325
|
+
signal?.addEventListener?.('abort', onAbort, { once: true });
|
|
326
|
+
try {
|
|
327
|
+
const audio = await api.downloadFile({
|
|
328
|
+
fileId: voice.fileId,
|
|
329
|
+
signal: controller.signal,
|
|
330
|
+
maxBytes: VOICE_MAX_BYTES,
|
|
331
|
+
});
|
|
332
|
+
const transcript = await transcriber.transcribe({ audio, voice, signal: controller.signal });
|
|
333
|
+
// Providers may return raw text; an empty result is not a transcript.
|
|
334
|
+
const text = typeof transcript === 'string' ? transcript.trim() : '';
|
|
335
|
+
message.content = text || voiceNote({ voice, reason: 'no speech recognized' });
|
|
336
|
+
} catch (error) {
|
|
337
|
+
if (signal?.aborted) return;
|
|
338
|
+
const reason = controller.signal.aborted
|
|
339
|
+
? `transcription timed out after ${formatDurationMs(timeoutMs)}`
|
|
340
|
+
: voiceFailureReason(error);
|
|
341
|
+
message.content = voiceNote({ voice, reason });
|
|
342
|
+
logFailure?.(reason, error);
|
|
343
|
+
} finally {
|
|
344
|
+
clearTimeout(timer);
|
|
345
|
+
signal?.removeEventListener?.('abort', onAbort);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
278
349
|
export function normalizeTelegramUpdate(update, {
|
|
279
350
|
botId,
|
|
280
351
|
username,
|
|
352
|
+
groupTriggers,
|
|
281
353
|
loadFile = async () => { throw new Error('Telegram file downloader is unavailable'); },
|
|
282
354
|
loadFileStream = loadFile,
|
|
283
355
|
loadReplyContent,
|
|
@@ -290,13 +362,21 @@ export function normalizeTelegramUpdate(update, {
|
|
|
290
362
|
|| !Number.isSafeInteger(messageId)) return null;
|
|
291
363
|
if (!['private', 'group', 'supergroup'].includes(message.chat?.type)) return null;
|
|
292
364
|
const direct = message.chat.type === 'private';
|
|
293
|
-
|
|
294
|
-
|
|
365
|
+
// A reply to the bot or an @username mention is the legacy "tagged" signal;
|
|
366
|
+
// the per-group rule decides whether it is enough (or unnecessary).
|
|
367
|
+
const tagged = String(message.reply_to_message?.from?.id ?? '') === String(botId)
|
|
295
368
|
|| mentionedUsername(message, username);
|
|
369
|
+
const addressed = direct || groupTriggerAddressed(groupTriggers, {
|
|
370
|
+
chatId: String(chatId),
|
|
371
|
+
senderId: String(senderId),
|
|
372
|
+
tagged,
|
|
373
|
+
});
|
|
296
374
|
const messageThreadId = Number.isSafeInteger(message.message_thread_id)
|
|
297
375
|
? message.message_thread_id : undefined;
|
|
298
376
|
const image = telegramImageSource(message, loadFile);
|
|
299
377
|
const file = telegramFileSource(message, loadFileStream);
|
|
378
|
+
// Voice notes carry no text; a speech service later fills `content` in.
|
|
379
|
+
const voice = telegramVoiceSource(message);
|
|
300
380
|
const conversationId = messageThreadId === undefined
|
|
301
381
|
? String(chatId) : `${chatId}:${messageThreadId}`;
|
|
302
382
|
const key = `${direct ? 'direct' : 'group'}:${conversationId}`;
|
|
@@ -330,6 +410,7 @@ export function normalizeTelegramUpdate(update, {
|
|
|
330
410
|
plainText: typeof message.text === 'string',
|
|
331
411
|
images: image ? [image] : [],
|
|
332
412
|
files: file ? [file] : [],
|
|
413
|
+
...(voice ? { voice } : {}),
|
|
333
414
|
...(replyTo ? { replyTo } : {}),
|
|
334
415
|
addressed,
|
|
335
416
|
reactionTarget: { chatId, messageId },
|
|
@@ -357,11 +438,6 @@ function telegramMessageId(value) {
|
|
|
357
438
|
return Number.isSafeInteger(value?.message_id) ? String(value.message_id) : null;
|
|
358
439
|
}
|
|
359
440
|
|
|
360
|
-
function telegramMessageUnchanged(error) {
|
|
361
|
-
return error?.providerCode === 400
|
|
362
|
-
&& /^(?:Bad Request: )?message is not modified(?::|$)/iu.test(error?.message ?? '');
|
|
363
|
-
}
|
|
364
|
-
|
|
365
441
|
function telegramFailure(error) {
|
|
366
442
|
const providerCode = Number(error?.providerCode);
|
|
367
443
|
const status = Number(error?.status);
|
|
@@ -391,12 +467,15 @@ class TelegramDeliveryStream {
|
|
|
391
467
|
#update;
|
|
392
468
|
#finish;
|
|
393
469
|
#fail;
|
|
470
|
+
#onCancel;
|
|
394
471
|
#logger;
|
|
395
472
|
#providerMessageIds;
|
|
396
473
|
#closed = false;
|
|
397
474
|
#lastUpdate = null;
|
|
398
475
|
#lastBlock = null;
|
|
399
476
|
#keepalive = false;
|
|
477
|
+
#previewAnswer = true;
|
|
478
|
+
#uniqueFrames = false;
|
|
400
479
|
#previewStopped = false;
|
|
401
480
|
#chain = Promise.resolve();
|
|
402
481
|
|
|
@@ -404,14 +483,18 @@ class TelegramDeliveryStream {
|
|
|
404
483
|
update,
|
|
405
484
|
finish,
|
|
406
485
|
fail,
|
|
486
|
+
onCancel = null,
|
|
407
487
|
providerMessageIds = [],
|
|
408
488
|
presentation,
|
|
409
489
|
logger,
|
|
410
490
|
keepalive = false,
|
|
491
|
+
previewAnswer = true,
|
|
492
|
+
uniqueFrames = false,
|
|
411
493
|
}) {
|
|
412
494
|
this.#update = update;
|
|
413
495
|
this.#finish = finish;
|
|
414
496
|
this.#fail = fail;
|
|
497
|
+
this.#onCancel = onCancel;
|
|
415
498
|
this.#providerMessageIds = providerMessageIds;
|
|
416
499
|
this.presentation = presentation;
|
|
417
500
|
this.#logger = logger;
|
|
@@ -419,6 +502,19 @@ class TelegramDeliveryStream {
|
|
|
419
502
|
// keepalive refresh; editing a real placeholder message with identical
|
|
420
503
|
// content would be rejected by the platform.
|
|
421
504
|
this.#keepalive = keepalive === true;
|
|
505
|
+
// The placeholder is deleted before the answer is sent, so mirroring the
|
|
506
|
+
// answer text into it would show the same reply twice: first as a run of
|
|
507
|
+
// edits, then again as the delivered message.
|
|
508
|
+
this.#previewAnswer = previewAnswer !== false;
|
|
509
|
+
// A numbered carrier rewrites one line with a different prefix, so the
|
|
510
|
+
// identical-text shortcut would swallow every frame after the first and the
|
|
511
|
+
// reader would still watch a frozen placeholder.
|
|
512
|
+
this.#uniqueFrames = uniqueFrames === true;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** Whether answer text may be shown in the carrier before it is delivered. */
|
|
516
|
+
get previewAnswer() {
|
|
517
|
+
return this.#previewAnswer;
|
|
422
518
|
}
|
|
423
519
|
|
|
424
520
|
get providerMessageIds() {
|
|
@@ -438,6 +534,14 @@ class TelegramDeliveryStream {
|
|
|
438
534
|
return run;
|
|
439
535
|
}
|
|
440
536
|
|
|
537
|
+
/** Queue a write that originates outside update(), such as a paced frame
|
|
538
|
+
* released by a timer. It runs on the same chain as finish()/fail(), so a
|
|
539
|
+
* slow edit is awaited before finalization instead of landing after the
|
|
540
|
+
* answer. */
|
|
541
|
+
enqueue(task) {
|
|
542
|
+
return this.#enqueue(task);
|
|
543
|
+
}
|
|
544
|
+
|
|
441
545
|
// Live drafts can block the user's composer. Drain any pending draft before
|
|
442
546
|
// the regular question/approval message clears it, and keep this turn's
|
|
443
547
|
// preview stopped so late progress cannot block the answer again.
|
|
@@ -452,7 +556,7 @@ class TelegramDeliveryStream {
|
|
|
452
556
|
const block = createTextDeliveryBlock(value);
|
|
453
557
|
this.#lastBlock = block;
|
|
454
558
|
const key = `${block.format}:${block.text}`;
|
|
455
|
-
if (key === this.#lastUpdate) return undefined;
|
|
559
|
+
if (!this.#uniqueFrames && key === this.#lastUpdate) return undefined;
|
|
456
560
|
this.#lastUpdate = key;
|
|
457
561
|
try {
|
|
458
562
|
return await this.#update(block);
|
|
@@ -501,6 +605,9 @@ class TelegramDeliveryStream {
|
|
|
501
605
|
|
|
502
606
|
cancel() {
|
|
503
607
|
this.#closed = true;
|
|
608
|
+
// Carrier-specific teardown (a paced progress window still holding a frame
|
|
609
|
+
// and its timer) lives with whoever opened the stream.
|
|
610
|
+
this.#onCancel?.();
|
|
504
611
|
}
|
|
505
612
|
}
|
|
506
613
|
|
|
@@ -567,11 +674,22 @@ export class TelegramBotClient {
|
|
|
567
674
|
#api;
|
|
568
675
|
#signal;
|
|
569
676
|
#logger;
|
|
677
|
+
#thinkingNumbering;
|
|
678
|
+
#thinkingIntervalMs;
|
|
570
679
|
|
|
571
|
-
constructor({
|
|
680
|
+
constructor({
|
|
681
|
+
api,
|
|
682
|
+
signal,
|
|
683
|
+
logger = console,
|
|
684
|
+
thinkingNumbering = false,
|
|
685
|
+
thinkingIntervalSeconds = 0,
|
|
686
|
+
}) {
|
|
572
687
|
this.#api = api;
|
|
573
688
|
this.#signal = signal;
|
|
574
689
|
this.#logger = logger;
|
|
690
|
+
// Read once: the runtime restarts whenever the owner changes either value.
|
|
691
|
+
this.#thinkingNumbering = normalizeThinkingNumbering(thinkingNumbering);
|
|
692
|
+
this.#thinkingIntervalMs = normalizeThinkingIntervalSeconds(thinkingIntervalSeconds) * 1_000;
|
|
575
693
|
}
|
|
576
694
|
|
|
577
695
|
async sendText(target, text) {
|
|
@@ -679,63 +797,14 @@ export class TelegramBotClient {
|
|
|
679
797
|
});
|
|
680
798
|
}
|
|
681
799
|
|
|
682
|
-
async #sendPlain(target, text
|
|
800
|
+
async #sendPlain(target, text) {
|
|
683
801
|
const chunks = splitTelegramRegularText(text);
|
|
684
|
-
const providerMessageIds =
|
|
685
|
-
|
|
686
|
-
: [String(placeholderMessageId)];
|
|
687
|
-
let firstUnsent = 0;
|
|
688
|
-
if (placeholderMessageId !== undefined) {
|
|
689
|
-
try {
|
|
690
|
-
await this.#api.editMessageText({
|
|
691
|
-
chatId: target.chatId,
|
|
692
|
-
messageId: placeholderMessageId,
|
|
693
|
-
text: chunks[0],
|
|
694
|
-
signal: this.#signal,
|
|
695
|
-
}).catch((error) => {
|
|
696
|
-
// The final answer may already be visible from the last progress edit.
|
|
697
|
-
if (!telegramMessageUnchanged(error)) throw error;
|
|
698
|
-
});
|
|
699
|
-
firstUnsent = 1;
|
|
700
|
-
} catch (error) {
|
|
701
|
-
const failure = telegramFailure(error);
|
|
702
|
-
if (failure.outcome === 'unknown') {
|
|
703
|
-
return deliveryResult('text-fallback', providerMessageIds, 'unknown', failure.reason);
|
|
704
|
-
}
|
|
705
|
-
|
|
706
|
-
const fallback = await this.#sendPlain(target, text);
|
|
707
|
-
const terminalText = fallback.deliveryOutcome === 'sent'
|
|
708
|
-
? t('回复已发送。')
|
|
709
|
-
: fallback.deliveryOutcome === 'unknown'
|
|
710
|
-
? t('回复发送结果未能确认。')
|
|
711
|
-
: t('消息发送失败,请稍后重试。');
|
|
712
|
-
try {
|
|
713
|
-
await this.#api.editMessageText({
|
|
714
|
-
chatId: target.chatId,
|
|
715
|
-
messageId: placeholderMessageId,
|
|
716
|
-
text: terminalText,
|
|
717
|
-
signal: this.#signal,
|
|
718
|
-
});
|
|
719
|
-
} catch (terminalError) {
|
|
720
|
-
this.#logger.warn?.(
|
|
721
|
-
'[dsh-im:telegram] unable to replace the processing placeholder:',
|
|
722
|
-
terminalError,
|
|
723
|
-
);
|
|
724
|
-
}
|
|
725
|
-
return deliveryResult(
|
|
726
|
-
'text-fallback',
|
|
727
|
-
[...providerMessageIds, ...fallback.providerMessageIds],
|
|
728
|
-
fallback.deliveryOutcome,
|
|
729
|
-
fallback.reason,
|
|
730
|
-
);
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
|
|
734
|
-
for (let index = firstUnsent; index < chunks.length; index += 1) {
|
|
802
|
+
const providerMessageIds = [];
|
|
803
|
+
for (const [index, chunk] of chunks.entries()) {
|
|
735
804
|
try {
|
|
736
805
|
const result = await this.#api.sendMessage({
|
|
737
806
|
chatId: target.chatId,
|
|
738
|
-
text:
|
|
807
|
+
text: chunk,
|
|
739
808
|
replyToMessageId: index === 0 ? target.replyToMessageId : undefined,
|
|
740
809
|
messageThreadId: target.messageThreadId,
|
|
741
810
|
signal: this.#signal,
|
|
@@ -752,9 +821,39 @@ export class TelegramBotClient {
|
|
|
752
821
|
);
|
|
753
822
|
}
|
|
754
823
|
}
|
|
824
|
+
// A resolved call is not a delivered answer: without a message id the
|
|
825
|
+
// reader may still be staring at nothing, so the final answer claims only
|
|
826
|
+
// what it can prove and lets the caller report the rest.
|
|
827
|
+
if (providerMessageIds.length !== chunks.length) {
|
|
828
|
+
return deliveryResult(
|
|
829
|
+
'text-fallback',
|
|
830
|
+
providerMessageIds,
|
|
831
|
+
'unknown',
|
|
832
|
+
'telegram-message-id-missing',
|
|
833
|
+
);
|
|
834
|
+
}
|
|
755
835
|
return deliveryResult('text-fallback', providerMessageIds);
|
|
756
836
|
}
|
|
757
837
|
|
|
838
|
+
/** Drop the progress placeholder before the answer is sent so the turn ends
|
|
839
|
+
* with a notification instead of a silent edit. Best-effort: Telegram only
|
|
840
|
+
* lets a bot delete its own messages for 48 hours, and a stale placeholder
|
|
841
|
+
* must never cost the reader the answer that was already produced. */
|
|
842
|
+
async #deletePlaceholder(target, messageId) {
|
|
843
|
+
try {
|
|
844
|
+
await this.#api.deleteMessage({
|
|
845
|
+
chatId: target.chatId,
|
|
846
|
+
messageId,
|
|
847
|
+
signal: this.#signal,
|
|
848
|
+
});
|
|
849
|
+
} catch (error) {
|
|
850
|
+
this.#logger.warn?.(
|
|
851
|
+
'[dsh-im:telegram] unable to delete the processing placeholder:',
|
|
852
|
+
error,
|
|
853
|
+
);
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
|
|
758
857
|
async #sendRich(target, block) {
|
|
759
858
|
if (block.format === 'plain') return this.#sendPlain(target, block.text);
|
|
760
859
|
|
|
@@ -800,77 +899,15 @@ export class TelegramBotClient {
|
|
|
800
899
|
);
|
|
801
900
|
}
|
|
802
901
|
}
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
let chunks;
|
|
814
|
-
try {
|
|
815
|
-
chunks = splitTelegramRichMarkdown(block.text);
|
|
816
|
-
} catch {
|
|
817
|
-
return this.#sendPlain(target, block.text, { placeholderMessageId: messageId });
|
|
818
|
-
}
|
|
819
|
-
const providerMessageIds = [String(messageId)];
|
|
820
|
-
try {
|
|
821
|
-
await this.#api.editMessageText({
|
|
822
|
-
chatId: target.chatId,
|
|
823
|
-
messageId,
|
|
824
|
-
richMessage: { markdown: chunks[0].markdown },
|
|
825
|
-
signal: this.#signal,
|
|
826
|
-
}).catch((error) => {
|
|
827
|
-
if (!telegramMessageUnchanged(error)) throw error;
|
|
828
|
-
});
|
|
829
|
-
} catch (error) {
|
|
830
|
-
const failure = telegramFailure(error);
|
|
831
|
-
if (failure.outcome === 'unknown') {
|
|
832
|
-
return deliveryResult(
|
|
833
|
-
'telegram-rich-final',
|
|
834
|
-
providerMessageIds,
|
|
835
|
-
'unknown',
|
|
836
|
-
failure.reason,
|
|
837
|
-
);
|
|
838
|
-
}
|
|
839
|
-
return this.#sendPlain(target, block.text, { placeholderMessageId: messageId });
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
for (const [offset, chunk] of chunks.slice(1).entries()) {
|
|
843
|
-
try {
|
|
844
|
-
const result = await this.#api.sendRichMessage({
|
|
845
|
-
chatId: target.chatId,
|
|
846
|
-
richMessage: { markdown: chunk.markdown },
|
|
847
|
-
messageThreadId: target.messageThreadId,
|
|
848
|
-
signal: this.#signal,
|
|
849
|
-
});
|
|
850
|
-
const id = telegramMessageId(result);
|
|
851
|
-
if (id) providerMessageIds.push(id);
|
|
852
|
-
} catch (error) {
|
|
853
|
-
const failure = telegramFailure(error);
|
|
854
|
-
if (failure.outcome === 'unknown') {
|
|
855
|
-
return deliveryResult(
|
|
856
|
-
'telegram-rich-final',
|
|
857
|
-
providerMessageIds,
|
|
858
|
-
'unknown',
|
|
859
|
-
failure.reason,
|
|
860
|
-
);
|
|
861
|
-
}
|
|
862
|
-
const remaining = chunks.slice(offset + 1).map((part) => part.source).join('');
|
|
863
|
-
const fallback = await this.#sendPlain({
|
|
864
|
-
...target,
|
|
865
|
-
replyToMessageId: undefined,
|
|
866
|
-
}, remaining);
|
|
867
|
-
return deliveryResult(
|
|
868
|
-
fallback.presentation,
|
|
869
|
-
[...providerMessageIds, ...fallback.providerMessageIds],
|
|
870
|
-
fallback.deliveryOutcome,
|
|
871
|
-
fallback.reason,
|
|
872
|
-
);
|
|
873
|
-
}
|
|
902
|
+
// Same proof as the plain path: a rich send that never returned an id
|
|
903
|
+
// cannot be reported as delivered.
|
|
904
|
+
if (providerMessageIds.length !== chunks.length) {
|
|
905
|
+
return deliveryResult(
|
|
906
|
+
'telegram-rich-final',
|
|
907
|
+
providerMessageIds,
|
|
908
|
+
'unknown',
|
|
909
|
+
'telegram-message-id-missing',
|
|
910
|
+
);
|
|
874
911
|
}
|
|
875
912
|
return deliveryResult('telegram-rich-final', providerMessageIds);
|
|
876
913
|
}
|
|
@@ -893,33 +930,120 @@ export class TelegramBotClient {
|
|
|
893
930
|
if (!Number.isSafeInteger(messageId)) {
|
|
894
931
|
throw new Error('Telegram did not return a placeholder message id');
|
|
895
932
|
}
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
if (block.format === 'plain') {
|
|
899
|
-
await this.#api.editMessageText({
|
|
900
|
-
chatId: target.chatId,
|
|
901
|
-
messageId,
|
|
902
|
-
text: block.text,
|
|
903
|
-
signal: this.#signal,
|
|
904
|
-
});
|
|
905
|
-
return deliveryResult('text-fallback', [String(messageId)]);
|
|
906
|
-
}
|
|
933
|
+
const editBlock = async (block) => {
|
|
934
|
+
if (block.format === 'plain') {
|
|
907
935
|
await this.#api.editMessageText({
|
|
908
936
|
chatId: target.chatId,
|
|
909
937
|
messageId,
|
|
910
|
-
|
|
938
|
+
text: block.text,
|
|
911
939
|
signal: this.#signal,
|
|
912
940
|
});
|
|
913
|
-
return deliveryResult('
|
|
941
|
+
return deliveryResult('text-fallback', [String(messageId)]);
|
|
942
|
+
}
|
|
943
|
+
await this.#api.editMessageText({
|
|
944
|
+
chatId: target.chatId,
|
|
945
|
+
messageId,
|
|
946
|
+
richMessage: { markdown: toTelegramRichMarkdown(block.text) },
|
|
947
|
+
signal: this.#signal,
|
|
948
|
+
});
|
|
949
|
+
return deliveryResult('telegram-rich-draft', [String(messageId)]);
|
|
950
|
+
};
|
|
951
|
+
// One message rewritten in place means a row of identical "Using bash"
|
|
952
|
+
// edits looks frozen. Numbering counts every progress frame of the turn and
|
|
953
|
+
// prefixes it, so the line keeps moving; pacing keeps the edits themselves
|
|
954
|
+
// rare and still lands the newest held frame when its window closes.
|
|
955
|
+
const numbering = this.#thinkingNumbering;
|
|
956
|
+
const intervalMs = this.#thinkingIntervalMs;
|
|
957
|
+
let sequence = 0;
|
|
958
|
+
let held = null;
|
|
959
|
+
let windowTimer = null;
|
|
960
|
+
let windowEndsAt = 0;
|
|
961
|
+
let closed = false;
|
|
962
|
+
let stream = null;
|
|
963
|
+
const clearWindowTimer = () => {
|
|
964
|
+
if (windowTimer === null) return;
|
|
965
|
+
clearTimeout(windowTimer);
|
|
966
|
+
windowTimer = null;
|
|
967
|
+
};
|
|
968
|
+
const sendHeld = async () => {
|
|
969
|
+
const frame = held;
|
|
970
|
+
held = null;
|
|
971
|
+
if (!frame || closed) return;
|
|
972
|
+
try {
|
|
973
|
+
await editBlock(frame);
|
|
974
|
+
} catch (error) {
|
|
975
|
+
this.#logger?.warn?.('[dsh-im:telegram] placeholder frame failed:', error);
|
|
976
|
+
}
|
|
977
|
+
};
|
|
978
|
+
const armWindowTimer = () => {
|
|
979
|
+
if (windowTimer !== null) return;
|
|
980
|
+
windowTimer = setTimeout(() => {
|
|
981
|
+
windowTimer = null;
|
|
982
|
+
windowEndsAt = Date.now() + intervalMs;
|
|
983
|
+
// The released frame enters the stream's queue instead of editing on its
|
|
984
|
+
// own: an unqueued edit could still be in flight while finish() deletes
|
|
985
|
+
// the placeholder and sends the answer, so the stale frame would land
|
|
986
|
+
// after the reply.
|
|
987
|
+
void stream.enqueue(() => sendHeld());
|
|
988
|
+
}, Math.max(0, windowEndsAt - Date.now()));
|
|
989
|
+
};
|
|
990
|
+
// Finalization takes whatever the window still holds: the last frame goes
|
|
991
|
+
// out before the answer, and nothing may start after it.
|
|
992
|
+
const drainHeld = async () => {
|
|
993
|
+
clearWindowTimer();
|
|
994
|
+
await sendHeld();
|
|
995
|
+
closed = true;
|
|
996
|
+
};
|
|
997
|
+
const pushProgress = async (block) => {
|
|
998
|
+
if (closed) return undefined;
|
|
999
|
+
sequence += 1;
|
|
1000
|
+
const framed = numbering && block.text
|
|
1001
|
+
? { ...block, text: `${sequence}. ${block.text}` }
|
|
1002
|
+
: block;
|
|
1003
|
+
if (intervalMs <= 0) return editBlock(framed);
|
|
1004
|
+
if (Date.now() >= windowEndsAt) {
|
|
1005
|
+
// The deadline has passed but its timer may not have run yet, and that
|
|
1006
|
+
// callback would release the frame this newer one supersedes. Drop both
|
|
1007
|
+
// the held frame and its timer before letting the new frame through.
|
|
1008
|
+
clearWindowTimer();
|
|
1009
|
+
windowEndsAt = Date.now() + intervalMs;
|
|
1010
|
+
held = null;
|
|
1011
|
+
return editBlock(framed);
|
|
1012
|
+
}
|
|
1013
|
+
held = framed;
|
|
1014
|
+
armWindowTimer();
|
|
1015
|
+
return undefined;
|
|
1016
|
+
};
|
|
1017
|
+
stream = new TelegramDeliveryStream({
|
|
1018
|
+
update: (block) => pushProgress(block),
|
|
1019
|
+
// The placeholder carries progress only: its last frame would be a silent
|
|
1020
|
+
// edit, so the answer goes out as its own message and Telegram notifies
|
|
1021
|
+
// the reader that the turn is over.
|
|
1022
|
+
finish: async (block) => {
|
|
1023
|
+
await drainHeld();
|
|
1024
|
+
await this.#deletePlaceholder(target, messageId);
|
|
1025
|
+
return this.#sendRich(target, block);
|
|
1026
|
+
},
|
|
1027
|
+
fail: async (block) => {
|
|
1028
|
+
await drainHeld();
|
|
1029
|
+
await this.#deletePlaceholder(target, messageId);
|
|
1030
|
+
return this.#sendPlain(target, block.text);
|
|
1031
|
+
},
|
|
1032
|
+
// A cancelled turn must not wake up later and rewrite the placeholder the
|
|
1033
|
+
// reader has already stopped watching.
|
|
1034
|
+
onCancel: () => {
|
|
1035
|
+
closed = true;
|
|
1036
|
+
clearWindowTimer();
|
|
1037
|
+
held = null;
|
|
914
1038
|
},
|
|
915
|
-
finish: (block) => this.#editRich(target, messageId, block),
|
|
916
|
-
fail: (block) => this.#sendPlain(target, block.text, {
|
|
917
|
-
placeholderMessageId: messageId,
|
|
918
|
-
}),
|
|
919
|
-
providerMessageIds: [String(messageId)],
|
|
920
1039
|
presentation: 'telegram-regular',
|
|
1040
|
+
// Answer text is not mirrored into the placeholder: it is deleted before
|
|
1041
|
+
// the real message goes out, so a preview would duplicate the reply.
|
|
1042
|
+
previewAnswer: false,
|
|
1043
|
+
uniqueFrames: numbering,
|
|
921
1044
|
logger: this.#logger,
|
|
922
1045
|
});
|
|
1046
|
+
return stream;
|
|
923
1047
|
}
|
|
924
1048
|
|
|
925
1049
|
async openStream(target) {
|
|
@@ -963,6 +1087,14 @@ export class TelegramBotClient {
|
|
|
963
1087
|
const providerMessageIds = [];
|
|
964
1088
|
let firstMessageId = null;
|
|
965
1089
|
let closed = false;
|
|
1090
|
+
// Numbering counts every frame of the turn, paced-away ones included, so the
|
|
1091
|
+
// gaps in the visible numbers tell how much was held back.
|
|
1092
|
+
const numbering = this.#thinkingNumbering;
|
|
1093
|
+
const intervalMs = this.#thinkingIntervalMs;
|
|
1094
|
+
let sequence = 0;
|
|
1095
|
+
let held = null;
|
|
1096
|
+
let windowTimer = null;
|
|
1097
|
+
let windowEndsAt = 0;
|
|
966
1098
|
const logger = this.#logger;
|
|
967
1099
|
const warnFailure = (label, error) => {
|
|
968
1100
|
logger?.warn?.(`[dsh-im:telegram] thinking stream ${label} failed:`, error);
|
|
@@ -981,6 +1113,66 @@ export class TelegramBotClient {
|
|
|
981
1113
|
providerMessageIds.push(String(id));
|
|
982
1114
|
}
|
|
983
1115
|
};
|
|
1116
|
+
const deliver = async (label, text) => {
|
|
1117
|
+
try {
|
|
1118
|
+
await sendLine(text);
|
|
1119
|
+
} catch (error) {
|
|
1120
|
+
warnFailure(label, error);
|
|
1121
|
+
}
|
|
1122
|
+
};
|
|
1123
|
+
// Trace sends run in the background: the window timer starts one and nobody
|
|
1124
|
+
// awaits it, so finish() would otherwise find an empty buffer and let the
|
|
1125
|
+
// answer overtake a trace request that is still on the wire.
|
|
1126
|
+
const inFlight = new Set();
|
|
1127
|
+
const track = (label, text) => {
|
|
1128
|
+
const send = deliver(label, text).finally(() => { inFlight.delete(send); });
|
|
1129
|
+
inFlight.add(send);
|
|
1130
|
+
return send;
|
|
1131
|
+
};
|
|
1132
|
+
// Settling one send can release another (a held frame), so drain in a loop.
|
|
1133
|
+
const settleInFlight = async () => {
|
|
1134
|
+
while (inFlight.size > 0) await Promise.all([...inFlight]);
|
|
1135
|
+
};
|
|
1136
|
+
const clearWindowTimer = () => {
|
|
1137
|
+
if (windowTimer === null) return;
|
|
1138
|
+
clearTimeout(windowTimer);
|
|
1139
|
+
windowTimer = null;
|
|
1140
|
+
};
|
|
1141
|
+
const sendHeld = () => {
|
|
1142
|
+
const frame = held;
|
|
1143
|
+
held = null;
|
|
1144
|
+
return frame ? track(frame.label, frame.text) : Promise.resolve();
|
|
1145
|
+
};
|
|
1146
|
+
const armWindowTimer = () => {
|
|
1147
|
+
if (windowTimer !== null) return;
|
|
1148
|
+
windowTimer = setTimeout(() => {
|
|
1149
|
+
windowTimer = null;
|
|
1150
|
+
windowEndsAt = Date.now() + intervalMs;
|
|
1151
|
+
// The window keeps only the newest frame, so a burst collapses to one
|
|
1152
|
+
// message instead of a queue of frames nobody wants to read.
|
|
1153
|
+
void sendHeld();
|
|
1154
|
+
}, Math.max(0, windowEndsAt - Date.now()));
|
|
1155
|
+
};
|
|
1156
|
+
/** One frame: immediate outside a window, otherwise the newest held one. */
|
|
1157
|
+
const emit = (label, text) => {
|
|
1158
|
+
if (closed) return Promise.resolve();
|
|
1159
|
+
sequence += 1;
|
|
1160
|
+
const frame = { label, text: numbering ? `${sequence} ${text}` : text };
|
|
1161
|
+
if (intervalMs <= 0) return track(frame.label, frame.text);
|
|
1162
|
+
if (Date.now() >= windowEndsAt) {
|
|
1163
|
+
// The deadline has passed but its timer may not have run yet, and that
|
|
1164
|
+
// callback would deliver the frame this newer one supersedes. Drop both
|
|
1165
|
+
// the held frame and its timer before letting the new frame through.
|
|
1166
|
+
clearWindowTimer();
|
|
1167
|
+
held = null;
|
|
1168
|
+
windowEndsAt = Date.now() + intervalMs;
|
|
1169
|
+
return track(frame.label, frame.text);
|
|
1170
|
+
}
|
|
1171
|
+
// Inside the window: replace whatever waited, never append.
|
|
1172
|
+
held = frame;
|
|
1173
|
+
armWindowTimer();
|
|
1174
|
+
return Promise.resolve();
|
|
1175
|
+
};
|
|
984
1176
|
return {
|
|
985
1177
|
get messageId() {
|
|
986
1178
|
return firstMessageId;
|
|
@@ -995,27 +1187,21 @@ export class TelegramBotClient {
|
|
|
995
1187
|
update: async () => {},
|
|
996
1188
|
refresh: async () => {},
|
|
997
1189
|
sendLine,
|
|
998
|
-
sendToolTrace: (name, argumentsValue) => (
|
|
999
|
-
|
|
1000
|
-
try {
|
|
1001
|
-
await sendLine(formatToolTrace(name, argumentsValue));
|
|
1002
|
-
} catch (error) {
|
|
1003
|
-
warnFailure('tool trace', error);
|
|
1004
|
-
}
|
|
1005
|
-
})(),
|
|
1006
|
-
sendThinking: (text) => (async () => {
|
|
1007
|
-
if (closed) return;
|
|
1190
|
+
sendToolTrace: (name, argumentsValue) => emit('tool trace', formatToolTrace(name, argumentsValue)),
|
|
1191
|
+
sendThinking: (text) => {
|
|
1008
1192
|
const line = formatThinkingLine(text);
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
await sendLine(line);
|
|
1012
|
-
} catch (error) {
|
|
1013
|
-
warnFailure('thinking line', error);
|
|
1014
|
-
}
|
|
1015
|
-
})(),
|
|
1193
|
+
return line ? emit('thinking line', line) : Promise.resolve();
|
|
1194
|
+
},
|
|
1016
1195
|
async finish(answer) {
|
|
1017
1196
|
if (closed) throw new Error('Message stream is already closed');
|
|
1018
1197
|
closed = true;
|
|
1198
|
+
// The held frame is the last thing the turn thought about, so it goes
|
|
1199
|
+
// out before the answer instead of after its own result. Then wait for
|
|
1200
|
+
// every trace still in flight, so none can land behind the answer; the
|
|
1201
|
+
// trace sends are already best-effort and never reject.
|
|
1202
|
+
clearWindowTimer();
|
|
1203
|
+
await sendHeld();
|
|
1204
|
+
await settleInFlight();
|
|
1019
1205
|
const format = answer && typeof answer === 'object' && answer.format === 'markdown'
|
|
1020
1206
|
? 'markdown'
|
|
1021
1207
|
: 'plain';
|
|
@@ -1084,6 +1270,9 @@ export class TelegramBotClient {
|
|
|
1084
1270
|
},
|
|
1085
1271
|
cancel() {
|
|
1086
1272
|
closed = true;
|
|
1273
|
+
// A cancelled turn must not leave a timer that sends a stale frame.
|
|
1274
|
+
clearWindowTimer();
|
|
1275
|
+
held = null;
|
|
1087
1276
|
},
|
|
1088
1277
|
};
|
|
1089
1278
|
}
|
|
@@ -1109,7 +1298,13 @@ export class TelegramRuntime {
|
|
|
1109
1298
|
#state;
|
|
1110
1299
|
#contextEnhancement;
|
|
1111
1300
|
#groupHistory;
|
|
1301
|
+
#groupTriggers;
|
|
1112
1302
|
#accessPolicy;
|
|
1303
|
+
#voice;
|
|
1304
|
+
#voiceTimeoutMs;
|
|
1305
|
+
#conversationQueue;
|
|
1306
|
+
/** Reasons already reported, so a broken recognizer logs once. */
|
|
1307
|
+
#voiceFailures = new Set();
|
|
1113
1308
|
#logger;
|
|
1114
1309
|
#diagnostics;
|
|
1115
1310
|
#replyTimeoutMs;
|
|
@@ -1140,6 +1335,8 @@ export class TelegramRuntime {
|
|
|
1140
1335
|
contextEnhancement,
|
|
1141
1336
|
groupHistory,
|
|
1142
1337
|
accessPolicy,
|
|
1338
|
+
voice = null,
|
|
1339
|
+
voiceTimeoutMs = 60_000,
|
|
1143
1340
|
logger = console,
|
|
1144
1341
|
replyTimeoutMs = 600_000,
|
|
1145
1342
|
createApi = (options) => new TelegramApi(options),
|
|
@@ -1155,7 +1352,20 @@ export class TelegramRuntime {
|
|
|
1155
1352
|
this.#state = state;
|
|
1156
1353
|
this.#contextEnhancement = contextEnhancement;
|
|
1157
1354
|
this.#groupHistory = groupHistory;
|
|
1355
|
+
// Rules change through the controller, which restarts the runtime, so the
|
|
1356
|
+
// normalized snapshot is read once per start.
|
|
1357
|
+
this.#groupTriggers = normalizeGroupTriggers(config.groupTriggers);
|
|
1158
1358
|
this.#accessPolicy = accessPolicy;
|
|
1359
|
+
// null when the Host mounts no speech service; voice messages then stay textless.
|
|
1360
|
+
this.#voice = voice;
|
|
1361
|
+
this.#voiceTimeoutMs = voiceTimeoutMs;
|
|
1362
|
+
// Voice prep and delivery are serialised per conversation, never per poll.
|
|
1363
|
+
this.#conversationQueue = createConversationQueue({
|
|
1364
|
+
onError: (error, key) => this.#logger.error?.(
|
|
1365
|
+
`[dsh-im:telegram] bot ${this.#config.botId} queued work failed for ${key}:`,
|
|
1366
|
+
error?.message ?? error,
|
|
1367
|
+
),
|
|
1368
|
+
});
|
|
1159
1369
|
this.#logger = logger; this.#diagnostics = createConnectionDiagnostics({ channel: 'telegram', logger });
|
|
1160
1370
|
this.#replyTimeoutMs = replyTimeoutMs;
|
|
1161
1371
|
this.#createApi = createApi;
|
|
@@ -1237,6 +1447,10 @@ export class TelegramRuntime {
|
|
|
1237
1447
|
token: this.#token,
|
|
1238
1448
|
fetchImpl: transport.fetchImpl,
|
|
1239
1449
|
FormDataImpl: transport.FormDataImpl,
|
|
1450
|
+
// Telegram budgets new messages per chat; the bot waits for a free slot
|
|
1451
|
+
// instead of dropping the message, and retries after a 429.
|
|
1452
|
+
sendLimitPerMinute: normalizeSendLimitPerMinute(this.#config?.sendLimitPerMinute),
|
|
1453
|
+
logger: this.#logger,
|
|
1240
1454
|
});
|
|
1241
1455
|
this.#api = api;
|
|
1242
1456
|
const bot = await api.getMe({ signal: controller.signal });
|
|
@@ -1262,6 +1476,9 @@ export class TelegramRuntime {
|
|
|
1262
1476
|
api,
|
|
1263
1477
|
signal: controller.signal,
|
|
1264
1478
|
logger: this.#logger,
|
|
1479
|
+
// Trace frames are numbered and paced per bot; 0 seconds means no pacing.
|
|
1480
|
+
thinkingNumbering: this.#config?.thinkingNumbering,
|
|
1481
|
+
thinkingIntervalSeconds: this.#config?.thinkingIntervalSeconds,
|
|
1265
1482
|
});
|
|
1266
1483
|
this.#bridge = new TelegramHarnessBridge({
|
|
1267
1484
|
bot: client,
|
|
@@ -1303,6 +1520,7 @@ export class TelegramRuntime {
|
|
|
1303
1520
|
);
|
|
1304
1521
|
}
|
|
1305
1522
|
}
|
|
1523
|
+
await this.#replayPendingVoice(controller.signal);
|
|
1306
1524
|
this.#pollTask = this.#poll(cursor, controller.signal);
|
|
1307
1525
|
this.#pollTask.catch((error) => {
|
|
1308
1526
|
if (controller.signal.aborted) return;
|
|
@@ -1368,6 +1586,132 @@ export class TelegramRuntime {
|
|
|
1368
1586
|
}
|
|
1369
1587
|
}
|
|
1370
1588
|
|
|
1589
|
+
/**
|
|
1590
|
+
* Queue one update: durable pending record first, then per-conversation work.
|
|
1591
|
+
*
|
|
1592
|
+
* Ordering inside a chat is kept, while other chats, callbacks and the cursor
|
|
1593
|
+
* keep moving. The pending entry is removed only once the bridge owns the
|
|
1594
|
+
* message, so a restart before that point can replay it.
|
|
1595
|
+
*/
|
|
1596
|
+
async #dispatchUpdate(update, message, contextSnapshot, signal) {
|
|
1597
|
+
const needsPreparation = Boolean(message.voice) && message.addressed === true
|
|
1598
|
+
&& !message.content.trim();
|
|
1599
|
+
const pendingId = `telegram-voice:${update.update_id}`;
|
|
1600
|
+
if (needsPreparation) {
|
|
1601
|
+
try {
|
|
1602
|
+
await this.#state.putPendingMessage({
|
|
1603
|
+
id: pendingId,
|
|
1604
|
+
key: message.conversationId,
|
|
1605
|
+
messageId: String(message.messageId),
|
|
1606
|
+
kind: message.kind,
|
|
1607
|
+
text: voiceNote({ voice: message.voice, reason: 'transcription pending' }),
|
|
1608
|
+
senderId: String(message.senderId),
|
|
1609
|
+
target: { voiceReplay: { update, contextSnapshot } },
|
|
1610
|
+
});
|
|
1611
|
+
} catch (error) {
|
|
1612
|
+
this.#logger.warn?.(
|
|
1613
|
+
`[dsh-im:telegram] bot ${this.#config.botId} could not persist a queued voice message:`,
|
|
1614
|
+
error?.message ?? error,
|
|
1615
|
+
);
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
let accepted = false;
|
|
1619
|
+
void this.#conversationQueue.run(message.conversationId, async () => {
|
|
1620
|
+
try {
|
|
1621
|
+
if (signal.aborted) return;
|
|
1622
|
+
if (needsPreparation) await this.#transcribeVoice(message, signal);
|
|
1623
|
+
if (signal.aborted) return;
|
|
1624
|
+
await captureGroupHistory(this.#groupHistory, message, groupHistoryEntry('telegram', update, message), {
|
|
1625
|
+
logger: this.#logger,
|
|
1626
|
+
});
|
|
1627
|
+
accepted = true;
|
|
1628
|
+
// The bridge owns turn ordering; awaiting it here would park the
|
|
1629
|
+
// conversation behind a turn that waits for the user.
|
|
1630
|
+
void this.#bridge.accept(message, { contextSnapshot }).catch((error) => {
|
|
1631
|
+
if (signal.aborted) return;
|
|
1632
|
+
this.#logger.error?.(
|
|
1633
|
+
`[dsh-im:telegram] bot ${this.#config.botId} message handling failed:`,
|
|
1634
|
+
extractConnectionEvidence(error).details,
|
|
1635
|
+
);
|
|
1636
|
+
});
|
|
1637
|
+
} finally {
|
|
1638
|
+
// A cancelled prepare keeps the record: the next start replays it.
|
|
1639
|
+
if (needsPreparation && accepted) {
|
|
1640
|
+
await this.#state.removePendingMessage(pendingId).catch(() => {});
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
});
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
/**
|
|
1647
|
+
* Replay voice messages whose preparation was interrupted by a restart.
|
|
1648
|
+
*
|
|
1649
|
+
* The raw update travels with the pending record, so the message is rebuilt
|
|
1650
|
+
* exactly as the poller first saw it.
|
|
1651
|
+
*/
|
|
1652
|
+
async #replayPendingVoice(signal) {
|
|
1653
|
+
let entries = [];
|
|
1654
|
+
try {
|
|
1655
|
+
entries = typeof this.#state.pendingMessages === 'function' ? this.#state.pendingMessages() : [];
|
|
1656
|
+
} catch {
|
|
1657
|
+
return;
|
|
1658
|
+
}
|
|
1659
|
+
for (const entry of entries) {
|
|
1660
|
+
const replayed = entry?.target?.voiceReplay;
|
|
1661
|
+
if (!replayed || !replayed.update) continue;
|
|
1662
|
+
if (signal.aborted) return;
|
|
1663
|
+
const message = normalizeTelegramUpdate(replayed.update, {
|
|
1664
|
+
botId: this.#config.platformId,
|
|
1665
|
+
username: this.#config.username,
|
|
1666
|
+
// Same rules the poller applied: a replayed group update must keep the
|
|
1667
|
+
// addressing decision that queued it.
|
|
1668
|
+
groupTriggers: this.#groupTriggers,
|
|
1669
|
+
loadFile: (fileId, options) => this.#api.downloadFile({ fileId, ...options }),
|
|
1670
|
+
loadFileStream: (fileId, options) => this.#api.downloadFileStream({ fileId, ...options }),
|
|
1671
|
+
loadReplyContent: (reference, options) => this.#loadReplyContent(reference, options),
|
|
1672
|
+
});
|
|
1673
|
+
if (!message) {
|
|
1674
|
+
await this.#state.removePendingMessage(entry.id).catch(() => {});
|
|
1675
|
+
continue;
|
|
1676
|
+
}
|
|
1677
|
+
this.#logger.warn?.(
|
|
1678
|
+
`[dsh-im:telegram] bot ${this.#config.botId} replaying an interrupted voice message`,
|
|
1679
|
+
);
|
|
1680
|
+
await this.#dispatchUpdate(replayed.update, message, replayed.contextSnapshot, signal);
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
|
|
1684
|
+
/**
|
|
1685
|
+
* Substitute a transcript — or an explicit "not transcribed" note — for an
|
|
1686
|
+
* empty voice message.
|
|
1687
|
+
*
|
|
1688
|
+
* The note is the model's input, not the user's answer: the channel never
|
|
1689
|
+
* phrases a reply on its own, and the note says plainly that no transcript
|
|
1690
|
+
* exists so nothing is invented from the audio.
|
|
1691
|
+
*/
|
|
1692
|
+
async #transcribeVoice(message, signal) {
|
|
1693
|
+
if (!voiceMessageAllowed(this.#accessPolicy, message)) return;
|
|
1694
|
+
await fillVoiceContent({
|
|
1695
|
+
message,
|
|
1696
|
+
voice: message.voice,
|
|
1697
|
+
api: this.#api,
|
|
1698
|
+
transcriber: this.#voice,
|
|
1699
|
+
timeoutMs: this.#voiceTimeoutMs,
|
|
1700
|
+
signal,
|
|
1701
|
+
logFailure: (reason, error) => this.#logVoiceFailure(reason, error),
|
|
1702
|
+
});
|
|
1703
|
+
}
|
|
1704
|
+
|
|
1705
|
+
/** Report one reason per runtime start; the model still gets a note every time. */
|
|
1706
|
+
#logVoiceFailure(reason, error) {
|
|
1707
|
+
if (this.#voiceFailures.has(reason)) return;
|
|
1708
|
+
this.#voiceFailures.add(reason);
|
|
1709
|
+
this.#logger.warn?.(
|
|
1710
|
+
`[dsh-im:telegram] bot ${this.#config.botId} voice transcription unavailable: ${reason}`,
|
|
1711
|
+
error?.message ?? '',
|
|
1712
|
+
);
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1371
1715
|
async #loadReplyContent(reference, { signal } = {}) {
|
|
1372
1716
|
const key = typeof reference?.conversationKey === 'string'
|
|
1373
1717
|
? reference.conversationKey.trim() : '';
|
|
@@ -1423,21 +1767,15 @@ export class TelegramRuntime {
|
|
|
1423
1767
|
const message = normalizeTelegramUpdate(update, {
|
|
1424
1768
|
botId: this.#config.platformId,
|
|
1425
1769
|
username: this.#config.username,
|
|
1770
|
+
groupTriggers: this.#groupTriggers,
|
|
1426
1771
|
loadFile: (fileId, options) => this.#api.downloadFile({ fileId, ...options }),
|
|
1427
1772
|
loadFileStream: (fileId, options) => this.#api.downloadFileStream({ fileId, ...options }),
|
|
1428
1773
|
loadReplyContent: (reference, options) => this.#loadReplyContent(reference, options),
|
|
1429
1774
|
});
|
|
1430
1775
|
if (message) {
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
void this.#bridge.accept(message, { contextSnapshot }).catch((error) => {
|
|
1435
|
-
if (signal.aborted) return;
|
|
1436
|
-
this.#logger.error?.(
|
|
1437
|
-
`[dsh-im:telegram] bot ${this.#config.botId} message handling failed:`,
|
|
1438
|
-
extractConnectionEvidence(error).details,
|
|
1439
|
-
);
|
|
1440
|
-
});
|
|
1776
|
+
// The queued record is written before the caller persists the cursor,
|
|
1777
|
+
// so a restart replays preparation instead of losing the update.
|
|
1778
|
+
await this.#dispatchUpdate(update, message, contextSnapshot, signal);
|
|
1441
1779
|
}
|
|
1442
1780
|
cursor = update.update_id + 1;
|
|
1443
1781
|
await this.#state.setCursor(cursor);
|
|
@@ -1447,6 +1785,7 @@ export class TelegramRuntime {
|
|
|
1447
1785
|
|
|
1448
1786
|
async stop() {
|
|
1449
1787
|
const pollTask = this.#pollTask;
|
|
1788
|
+
const queued = this.#conversationQueue.idle();
|
|
1450
1789
|
const bridge = this.#bridge;
|
|
1451
1790
|
const httpTransport = this.#httpTransport;
|
|
1452
1791
|
this.#abortController?.abort();
|
|
@@ -1459,6 +1798,11 @@ export class TelegramRuntime {
|
|
|
1459
1798
|
pollTask?.catch(() => undefined) ?? Promise.resolve(),
|
|
1460
1799
|
new Promise((resolve) => setTimeout(resolve, 2_000)),
|
|
1461
1800
|
]);
|
|
1801
|
+
// Queued per-conversation work settles on its own deadline, never shutdown.
|
|
1802
|
+
await Promise.race([
|
|
1803
|
+
queued,
|
|
1804
|
+
new Promise((resolve) => setTimeout(resolve, 2_000)),
|
|
1805
|
+
]);
|
|
1462
1806
|
await Promise.race([
|
|
1463
1807
|
bridge?.waitForIdle() ?? Promise.resolve(),
|
|
1464
1808
|
new Promise((resolve) => setTimeout(resolve, 2_000)),
|