@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
|
@@ -11,12 +11,18 @@ import { SHARED_COMMAND_CATALOG, commandsForChannel } from '../shared/command-ca
|
|
|
11
11
|
import { COMMANDS_MENU_BUTTON, TelegramApi, validateTelegramCommands } from './telegram-api.mjs';
|
|
12
12
|
import { createTelegramHttpTransport } from './telegram-http.mjs';
|
|
13
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';
|
|
14
17
|
import {
|
|
15
18
|
splitTelegramRegularText,
|
|
16
19
|
splitTelegramRichMarkdown,
|
|
17
20
|
toTelegramRichMarkdown,
|
|
18
21
|
} from './telegram-rich-message.mjs';
|
|
19
22
|
import {
|
|
23
|
+
normalizeThinkingIntervalSeconds,
|
|
24
|
+
normalizeThinkingNumbering,
|
|
25
|
+
normalizeSendLimitPerMinute,
|
|
20
26
|
TELEGRAM_ACCESS_MODES,
|
|
21
27
|
} from './config-store.mjs';
|
|
22
28
|
|
|
@@ -276,6 +282,70 @@ export function normalizeTelegramCallback(update, { botId } = {}) {
|
|
|
276
282
|
};
|
|
277
283
|
}
|
|
278
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
|
+
|
|
279
349
|
export function normalizeTelegramUpdate(update, {
|
|
280
350
|
botId,
|
|
281
351
|
username,
|
|
@@ -305,6 +375,8 @@ export function normalizeTelegramUpdate(update, {
|
|
|
305
375
|
? message.message_thread_id : undefined;
|
|
306
376
|
const image = telegramImageSource(message, loadFile);
|
|
307
377
|
const file = telegramFileSource(message, loadFileStream);
|
|
378
|
+
// Voice notes carry no text; a speech service later fills `content` in.
|
|
379
|
+
const voice = telegramVoiceSource(message);
|
|
308
380
|
const conversationId = messageThreadId === undefined
|
|
309
381
|
? String(chatId) : `${chatId}:${messageThreadId}`;
|
|
310
382
|
const key = `${direct ? 'direct' : 'group'}:${conversationId}`;
|
|
@@ -338,6 +410,7 @@ export function normalizeTelegramUpdate(update, {
|
|
|
338
410
|
plainText: typeof message.text === 'string',
|
|
339
411
|
images: image ? [image] : [],
|
|
340
412
|
files: file ? [file] : [],
|
|
413
|
+
...(voice ? { voice } : {}),
|
|
341
414
|
...(replyTo ? { replyTo } : {}),
|
|
342
415
|
addressed,
|
|
343
416
|
reactionTarget: { chatId, messageId },
|
|
@@ -365,11 +438,6 @@ function telegramMessageId(value) {
|
|
|
365
438
|
return Number.isSafeInteger(value?.message_id) ? String(value.message_id) : null;
|
|
366
439
|
}
|
|
367
440
|
|
|
368
|
-
function telegramMessageUnchanged(error) {
|
|
369
|
-
return error?.providerCode === 400
|
|
370
|
-
&& /^(?:Bad Request: )?message is not modified(?::|$)/iu.test(error?.message ?? '');
|
|
371
|
-
}
|
|
372
|
-
|
|
373
441
|
function telegramFailure(error) {
|
|
374
442
|
const providerCode = Number(error?.providerCode);
|
|
375
443
|
const status = Number(error?.status);
|
|
@@ -399,12 +467,15 @@ class TelegramDeliveryStream {
|
|
|
399
467
|
#update;
|
|
400
468
|
#finish;
|
|
401
469
|
#fail;
|
|
470
|
+
#onCancel;
|
|
402
471
|
#logger;
|
|
403
472
|
#providerMessageIds;
|
|
404
473
|
#closed = false;
|
|
405
474
|
#lastUpdate = null;
|
|
406
475
|
#lastBlock = null;
|
|
407
476
|
#keepalive = false;
|
|
477
|
+
#previewAnswer = true;
|
|
478
|
+
#uniqueFrames = false;
|
|
408
479
|
#previewStopped = false;
|
|
409
480
|
#chain = Promise.resolve();
|
|
410
481
|
|
|
@@ -412,14 +483,18 @@ class TelegramDeliveryStream {
|
|
|
412
483
|
update,
|
|
413
484
|
finish,
|
|
414
485
|
fail,
|
|
486
|
+
onCancel = null,
|
|
415
487
|
providerMessageIds = [],
|
|
416
488
|
presentation,
|
|
417
489
|
logger,
|
|
418
490
|
keepalive = false,
|
|
491
|
+
previewAnswer = true,
|
|
492
|
+
uniqueFrames = false,
|
|
419
493
|
}) {
|
|
420
494
|
this.#update = update;
|
|
421
495
|
this.#finish = finish;
|
|
422
496
|
this.#fail = fail;
|
|
497
|
+
this.#onCancel = onCancel;
|
|
423
498
|
this.#providerMessageIds = providerMessageIds;
|
|
424
499
|
this.presentation = presentation;
|
|
425
500
|
this.#logger = logger;
|
|
@@ -427,6 +502,19 @@ class TelegramDeliveryStream {
|
|
|
427
502
|
// keepalive refresh; editing a real placeholder message with identical
|
|
428
503
|
// content would be rejected by the platform.
|
|
429
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;
|
|
430
518
|
}
|
|
431
519
|
|
|
432
520
|
get providerMessageIds() {
|
|
@@ -446,6 +534,14 @@ class TelegramDeliveryStream {
|
|
|
446
534
|
return run;
|
|
447
535
|
}
|
|
448
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
|
+
|
|
449
545
|
// Live drafts can block the user's composer. Drain any pending draft before
|
|
450
546
|
// the regular question/approval message clears it, and keep this turn's
|
|
451
547
|
// preview stopped so late progress cannot block the answer again.
|
|
@@ -460,7 +556,7 @@ class TelegramDeliveryStream {
|
|
|
460
556
|
const block = createTextDeliveryBlock(value);
|
|
461
557
|
this.#lastBlock = block;
|
|
462
558
|
const key = `${block.format}:${block.text}`;
|
|
463
|
-
if (key === this.#lastUpdate) return undefined;
|
|
559
|
+
if (!this.#uniqueFrames && key === this.#lastUpdate) return undefined;
|
|
464
560
|
this.#lastUpdate = key;
|
|
465
561
|
try {
|
|
466
562
|
return await this.#update(block);
|
|
@@ -509,6 +605,9 @@ class TelegramDeliveryStream {
|
|
|
509
605
|
|
|
510
606
|
cancel() {
|
|
511
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?.();
|
|
512
611
|
}
|
|
513
612
|
}
|
|
514
613
|
|
|
@@ -575,11 +674,22 @@ export class TelegramBotClient {
|
|
|
575
674
|
#api;
|
|
576
675
|
#signal;
|
|
577
676
|
#logger;
|
|
677
|
+
#thinkingNumbering;
|
|
678
|
+
#thinkingIntervalMs;
|
|
578
679
|
|
|
579
|
-
constructor({
|
|
680
|
+
constructor({
|
|
681
|
+
api,
|
|
682
|
+
signal,
|
|
683
|
+
logger = console,
|
|
684
|
+
thinkingNumbering = false,
|
|
685
|
+
thinkingIntervalSeconds = 0,
|
|
686
|
+
}) {
|
|
580
687
|
this.#api = api;
|
|
581
688
|
this.#signal = signal;
|
|
582
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;
|
|
583
693
|
}
|
|
584
694
|
|
|
585
695
|
async sendText(target, text) {
|
|
@@ -687,63 +797,14 @@ export class TelegramBotClient {
|
|
|
687
797
|
});
|
|
688
798
|
}
|
|
689
799
|
|
|
690
|
-
async #sendPlain(target, text
|
|
800
|
+
async #sendPlain(target, text) {
|
|
691
801
|
const chunks = splitTelegramRegularText(text);
|
|
692
|
-
const providerMessageIds =
|
|
693
|
-
|
|
694
|
-
: [String(placeholderMessageId)];
|
|
695
|
-
let firstUnsent = 0;
|
|
696
|
-
if (placeholderMessageId !== undefined) {
|
|
697
|
-
try {
|
|
698
|
-
await this.#api.editMessageText({
|
|
699
|
-
chatId: target.chatId,
|
|
700
|
-
messageId: placeholderMessageId,
|
|
701
|
-
text: chunks[0],
|
|
702
|
-
signal: this.#signal,
|
|
703
|
-
}).catch((error) => {
|
|
704
|
-
// The final answer may already be visible from the last progress edit.
|
|
705
|
-
if (!telegramMessageUnchanged(error)) throw error;
|
|
706
|
-
});
|
|
707
|
-
firstUnsent = 1;
|
|
708
|
-
} catch (error) {
|
|
709
|
-
const failure = telegramFailure(error);
|
|
710
|
-
if (failure.outcome === 'unknown') {
|
|
711
|
-
return deliveryResult('text-fallback', providerMessageIds, 'unknown', failure.reason);
|
|
712
|
-
}
|
|
713
|
-
|
|
714
|
-
const fallback = await this.#sendPlain(target, text);
|
|
715
|
-
const terminalText = fallback.deliveryOutcome === 'sent'
|
|
716
|
-
? t('回复已发送。')
|
|
717
|
-
: fallback.deliveryOutcome === 'unknown'
|
|
718
|
-
? t('回复发送结果未能确认。')
|
|
719
|
-
: t('消息发送失败,请稍后重试。');
|
|
720
|
-
try {
|
|
721
|
-
await this.#api.editMessageText({
|
|
722
|
-
chatId: target.chatId,
|
|
723
|
-
messageId: placeholderMessageId,
|
|
724
|
-
text: terminalText,
|
|
725
|
-
signal: this.#signal,
|
|
726
|
-
});
|
|
727
|
-
} catch (terminalError) {
|
|
728
|
-
this.#logger.warn?.(
|
|
729
|
-
'[dsh-im:telegram] unable to replace the processing placeholder:',
|
|
730
|
-
terminalError,
|
|
731
|
-
);
|
|
732
|
-
}
|
|
733
|
-
return deliveryResult(
|
|
734
|
-
'text-fallback',
|
|
735
|
-
[...providerMessageIds, ...fallback.providerMessageIds],
|
|
736
|
-
fallback.deliveryOutcome,
|
|
737
|
-
fallback.reason,
|
|
738
|
-
);
|
|
739
|
-
}
|
|
740
|
-
}
|
|
741
|
-
|
|
742
|
-
for (let index = firstUnsent; index < chunks.length; index += 1) {
|
|
802
|
+
const providerMessageIds = [];
|
|
803
|
+
for (const [index, chunk] of chunks.entries()) {
|
|
743
804
|
try {
|
|
744
805
|
const result = await this.#api.sendMessage({
|
|
745
806
|
chatId: target.chatId,
|
|
746
|
-
text:
|
|
807
|
+
text: chunk,
|
|
747
808
|
replyToMessageId: index === 0 ? target.replyToMessageId : undefined,
|
|
748
809
|
messageThreadId: target.messageThreadId,
|
|
749
810
|
signal: this.#signal,
|
|
@@ -760,9 +821,39 @@ export class TelegramBotClient {
|
|
|
760
821
|
);
|
|
761
822
|
}
|
|
762
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
|
+
}
|
|
763
835
|
return deliveryResult('text-fallback', providerMessageIds);
|
|
764
836
|
}
|
|
765
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
|
+
|
|
766
857
|
async #sendRich(target, block) {
|
|
767
858
|
if (block.format === 'plain') return this.#sendPlain(target, block.text);
|
|
768
859
|
|
|
@@ -808,77 +899,15 @@ export class TelegramBotClient {
|
|
|
808
899
|
);
|
|
809
900
|
}
|
|
810
901
|
}
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
let chunks;
|
|
822
|
-
try {
|
|
823
|
-
chunks = splitTelegramRichMarkdown(block.text);
|
|
824
|
-
} catch {
|
|
825
|
-
return this.#sendPlain(target, block.text, { placeholderMessageId: messageId });
|
|
826
|
-
}
|
|
827
|
-
const providerMessageIds = [String(messageId)];
|
|
828
|
-
try {
|
|
829
|
-
await this.#api.editMessageText({
|
|
830
|
-
chatId: target.chatId,
|
|
831
|
-
messageId,
|
|
832
|
-
richMessage: { markdown: chunks[0].markdown },
|
|
833
|
-
signal: this.#signal,
|
|
834
|
-
}).catch((error) => {
|
|
835
|
-
if (!telegramMessageUnchanged(error)) throw error;
|
|
836
|
-
});
|
|
837
|
-
} catch (error) {
|
|
838
|
-
const failure = telegramFailure(error);
|
|
839
|
-
if (failure.outcome === 'unknown') {
|
|
840
|
-
return deliveryResult(
|
|
841
|
-
'telegram-rich-final',
|
|
842
|
-
providerMessageIds,
|
|
843
|
-
'unknown',
|
|
844
|
-
failure.reason,
|
|
845
|
-
);
|
|
846
|
-
}
|
|
847
|
-
return this.#sendPlain(target, block.text, { placeholderMessageId: messageId });
|
|
848
|
-
}
|
|
849
|
-
|
|
850
|
-
for (const [offset, chunk] of chunks.slice(1).entries()) {
|
|
851
|
-
try {
|
|
852
|
-
const result = await this.#api.sendRichMessage({
|
|
853
|
-
chatId: target.chatId,
|
|
854
|
-
richMessage: { markdown: chunk.markdown },
|
|
855
|
-
messageThreadId: target.messageThreadId,
|
|
856
|
-
signal: this.#signal,
|
|
857
|
-
});
|
|
858
|
-
const id = telegramMessageId(result);
|
|
859
|
-
if (id) providerMessageIds.push(id);
|
|
860
|
-
} catch (error) {
|
|
861
|
-
const failure = telegramFailure(error);
|
|
862
|
-
if (failure.outcome === 'unknown') {
|
|
863
|
-
return deliveryResult(
|
|
864
|
-
'telegram-rich-final',
|
|
865
|
-
providerMessageIds,
|
|
866
|
-
'unknown',
|
|
867
|
-
failure.reason,
|
|
868
|
-
);
|
|
869
|
-
}
|
|
870
|
-
const remaining = chunks.slice(offset + 1).map((part) => part.source).join('');
|
|
871
|
-
const fallback = await this.#sendPlain({
|
|
872
|
-
...target,
|
|
873
|
-
replyToMessageId: undefined,
|
|
874
|
-
}, remaining);
|
|
875
|
-
return deliveryResult(
|
|
876
|
-
fallback.presentation,
|
|
877
|
-
[...providerMessageIds, ...fallback.providerMessageIds],
|
|
878
|
-
fallback.deliveryOutcome,
|
|
879
|
-
fallback.reason,
|
|
880
|
-
);
|
|
881
|
-
}
|
|
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
|
+
);
|
|
882
911
|
}
|
|
883
912
|
return deliveryResult('telegram-rich-final', providerMessageIds);
|
|
884
913
|
}
|
|
@@ -901,33 +930,120 @@ export class TelegramBotClient {
|
|
|
901
930
|
if (!Number.isSafeInteger(messageId)) {
|
|
902
931
|
throw new Error('Telegram did not return a placeholder message id');
|
|
903
932
|
}
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
if (block.format === 'plain') {
|
|
907
|
-
await this.#api.editMessageText({
|
|
908
|
-
chatId: target.chatId,
|
|
909
|
-
messageId,
|
|
910
|
-
text: block.text,
|
|
911
|
-
signal: this.#signal,
|
|
912
|
-
});
|
|
913
|
-
return deliveryResult('text-fallback', [String(messageId)]);
|
|
914
|
-
}
|
|
933
|
+
const editBlock = async (block) => {
|
|
934
|
+
if (block.format === 'plain') {
|
|
915
935
|
await this.#api.editMessageText({
|
|
916
936
|
chatId: target.chatId,
|
|
917
937
|
messageId,
|
|
918
|
-
|
|
938
|
+
text: block.text,
|
|
919
939
|
signal: this.#signal,
|
|
920
940
|
});
|
|
921
|
-
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;
|
|
922
1038
|
},
|
|
923
|
-
finish: (block) => this.#editRich(target, messageId, block),
|
|
924
|
-
fail: (block) => this.#sendPlain(target, block.text, {
|
|
925
|
-
placeholderMessageId: messageId,
|
|
926
|
-
}),
|
|
927
|
-
providerMessageIds: [String(messageId)],
|
|
928
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,
|
|
929
1044
|
logger: this.#logger,
|
|
930
1045
|
});
|
|
1046
|
+
return stream;
|
|
931
1047
|
}
|
|
932
1048
|
|
|
933
1049
|
async openStream(target) {
|
|
@@ -971,6 +1087,14 @@ export class TelegramBotClient {
|
|
|
971
1087
|
const providerMessageIds = [];
|
|
972
1088
|
let firstMessageId = null;
|
|
973
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;
|
|
974
1098
|
const logger = this.#logger;
|
|
975
1099
|
const warnFailure = (label, error) => {
|
|
976
1100
|
logger?.warn?.(`[dsh-im:telegram] thinking stream ${label} failed:`, error);
|
|
@@ -989,6 +1113,66 @@ export class TelegramBotClient {
|
|
|
989
1113
|
providerMessageIds.push(String(id));
|
|
990
1114
|
}
|
|
991
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
|
+
};
|
|
992
1176
|
return {
|
|
993
1177
|
get messageId() {
|
|
994
1178
|
return firstMessageId;
|
|
@@ -1003,27 +1187,21 @@ export class TelegramBotClient {
|
|
|
1003
1187
|
update: async () => {},
|
|
1004
1188
|
refresh: async () => {},
|
|
1005
1189
|
sendLine,
|
|
1006
|
-
sendToolTrace: (name, argumentsValue) => (
|
|
1007
|
-
|
|
1008
|
-
try {
|
|
1009
|
-
await sendLine(formatToolTrace(name, argumentsValue));
|
|
1010
|
-
} catch (error) {
|
|
1011
|
-
warnFailure('tool trace', error);
|
|
1012
|
-
}
|
|
1013
|
-
})(),
|
|
1014
|
-
sendThinking: (text) => (async () => {
|
|
1015
|
-
if (closed) return;
|
|
1190
|
+
sendToolTrace: (name, argumentsValue) => emit('tool trace', formatToolTrace(name, argumentsValue)),
|
|
1191
|
+
sendThinking: (text) => {
|
|
1016
1192
|
const line = formatThinkingLine(text);
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
await sendLine(line);
|
|
1020
|
-
} catch (error) {
|
|
1021
|
-
warnFailure('thinking line', error);
|
|
1022
|
-
}
|
|
1023
|
-
})(),
|
|
1193
|
+
return line ? emit('thinking line', line) : Promise.resolve();
|
|
1194
|
+
},
|
|
1024
1195
|
async finish(answer) {
|
|
1025
1196
|
if (closed) throw new Error('Message stream is already closed');
|
|
1026
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();
|
|
1027
1205
|
const format = answer && typeof answer === 'object' && answer.format === 'markdown'
|
|
1028
1206
|
? 'markdown'
|
|
1029
1207
|
: 'plain';
|
|
@@ -1092,6 +1270,9 @@ export class TelegramBotClient {
|
|
|
1092
1270
|
},
|
|
1093
1271
|
cancel() {
|
|
1094
1272
|
closed = true;
|
|
1273
|
+
// A cancelled turn must not leave a timer that sends a stale frame.
|
|
1274
|
+
clearWindowTimer();
|
|
1275
|
+
held = null;
|
|
1095
1276
|
},
|
|
1096
1277
|
};
|
|
1097
1278
|
}
|
|
@@ -1119,6 +1300,11 @@ export class TelegramRuntime {
|
|
|
1119
1300
|
#groupHistory;
|
|
1120
1301
|
#groupTriggers;
|
|
1121
1302
|
#accessPolicy;
|
|
1303
|
+
#voice;
|
|
1304
|
+
#voiceTimeoutMs;
|
|
1305
|
+
#conversationQueue;
|
|
1306
|
+
/** Reasons already reported, so a broken recognizer logs once. */
|
|
1307
|
+
#voiceFailures = new Set();
|
|
1122
1308
|
#logger;
|
|
1123
1309
|
#diagnostics;
|
|
1124
1310
|
#replyTimeoutMs;
|
|
@@ -1149,6 +1335,8 @@ export class TelegramRuntime {
|
|
|
1149
1335
|
contextEnhancement,
|
|
1150
1336
|
groupHistory,
|
|
1151
1337
|
accessPolicy,
|
|
1338
|
+
voice = null,
|
|
1339
|
+
voiceTimeoutMs = 60_000,
|
|
1152
1340
|
logger = console,
|
|
1153
1341
|
replyTimeoutMs = 600_000,
|
|
1154
1342
|
createApi = (options) => new TelegramApi(options),
|
|
@@ -1168,6 +1356,16 @@ export class TelegramRuntime {
|
|
|
1168
1356
|
// normalized snapshot is read once per start.
|
|
1169
1357
|
this.#groupTriggers = normalizeGroupTriggers(config.groupTriggers);
|
|
1170
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
|
+
});
|
|
1171
1369
|
this.#logger = logger; this.#diagnostics = createConnectionDiagnostics({ channel: 'telegram', logger });
|
|
1172
1370
|
this.#replyTimeoutMs = replyTimeoutMs;
|
|
1173
1371
|
this.#createApi = createApi;
|
|
@@ -1249,6 +1447,10 @@ export class TelegramRuntime {
|
|
|
1249
1447
|
token: this.#token,
|
|
1250
1448
|
fetchImpl: transport.fetchImpl,
|
|
1251
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,
|
|
1252
1454
|
});
|
|
1253
1455
|
this.#api = api;
|
|
1254
1456
|
const bot = await api.getMe({ signal: controller.signal });
|
|
@@ -1274,6 +1476,9 @@ export class TelegramRuntime {
|
|
|
1274
1476
|
api,
|
|
1275
1477
|
signal: controller.signal,
|
|
1276
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,
|
|
1277
1482
|
});
|
|
1278
1483
|
this.#bridge = new TelegramHarnessBridge({
|
|
1279
1484
|
bot: client,
|
|
@@ -1315,6 +1520,7 @@ export class TelegramRuntime {
|
|
|
1315
1520
|
);
|
|
1316
1521
|
}
|
|
1317
1522
|
}
|
|
1523
|
+
await this.#replayPendingVoice(controller.signal);
|
|
1318
1524
|
this.#pollTask = this.#poll(cursor, controller.signal);
|
|
1319
1525
|
this.#pollTask.catch((error) => {
|
|
1320
1526
|
if (controller.signal.aborted) return;
|
|
@@ -1380,6 +1586,132 @@ export class TelegramRuntime {
|
|
|
1380
1586
|
}
|
|
1381
1587
|
}
|
|
1382
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
|
+
|
|
1383
1715
|
async #loadReplyContent(reference, { signal } = {}) {
|
|
1384
1716
|
const key = typeof reference?.conversationKey === 'string'
|
|
1385
1717
|
? reference.conversationKey.trim() : '';
|
|
@@ -1441,16 +1773,9 @@ export class TelegramRuntime {
|
|
|
1441
1773
|
loadReplyContent: (reference, options) => this.#loadReplyContent(reference, options),
|
|
1442
1774
|
});
|
|
1443
1775
|
if (message) {
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
void this.#bridge.accept(message, { contextSnapshot }).catch((error) => {
|
|
1448
|
-
if (signal.aborted) return;
|
|
1449
|
-
this.#logger.error?.(
|
|
1450
|
-
`[dsh-im:telegram] bot ${this.#config.botId} message handling failed:`,
|
|
1451
|
-
extractConnectionEvidence(error).details,
|
|
1452
|
-
);
|
|
1453
|
-
});
|
|
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);
|
|
1454
1779
|
}
|
|
1455
1780
|
cursor = update.update_id + 1;
|
|
1456
1781
|
await this.#state.setCursor(cursor);
|
|
@@ -1460,6 +1785,7 @@ export class TelegramRuntime {
|
|
|
1460
1785
|
|
|
1461
1786
|
async stop() {
|
|
1462
1787
|
const pollTask = this.#pollTask;
|
|
1788
|
+
const queued = this.#conversationQueue.idle();
|
|
1463
1789
|
const bridge = this.#bridge;
|
|
1464
1790
|
const httpTransport = this.#httpTransport;
|
|
1465
1791
|
this.#abortController?.abort();
|
|
@@ -1472,6 +1798,11 @@ export class TelegramRuntime {
|
|
|
1472
1798
|
pollTask?.catch(() => undefined) ?? Promise.resolve(),
|
|
1473
1799
|
new Promise((resolve) => setTimeout(resolve, 2_000)),
|
|
1474
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
|
+
]);
|
|
1475
1806
|
await Promise.race([
|
|
1476
1807
|
bridge?.waitForIdle() ?? Promise.resolve(),
|
|
1477
1808
|
new Promise((resolve) => setTimeout(resolve, 2_000)),
|