@xmanrui/dsh-im 5.4.0 → 5.6.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 +46 -5
- package/README.md +46 -5
- package/lib/client.js +2579 -664
- package/lib/index.js +406 -339
- package/package.json +4 -4
- package/plugin-src/client/channel-card-meta.js +6 -2
- package/plugin-src/client/channels/dingtalk/index.js +12 -9
- package/plugin-src/client/channels/feishu/group-settings.js +5 -5
- package/plugin-src/client/channels/feishu/index.js +33 -25
- package/plugin-src/client/channels/qq/index.js +5 -5
- package/plugin-src/client/channels/shared/token-api.js +25 -7
- package/plugin-src/client/channels/shared/token-channel.js +18 -11
- 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/channels/wecom/index.js +5 -5
- package/plugin-src/client/channels/wecom-app/index.js +3 -3
- package/plugin-src/client/channels/weixin/index.js +2 -2
- package/plugin-src/client/channels/whatsapp/index.js +6 -6
- package/plugin-src/client/credential-binding.js +3 -2
- package/plugin-src/client/delivery-settings.js +4 -4
- package/plugin-src/client/ds-bot-settings.js +3 -3
- package/plugin-src/client/global-settings.js +5 -2
- package/plugin-src/client/i18n-ru.js +1637 -0
- package/plugin-src/client/i18n.js +281 -124
- 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 +18 -6
- package/src/channels/dingtalk/dingtalk-bridge.mjs +1 -0
- package/src/channels/feishu/bridge.mjs +107 -7
- package/src/channels/feishu/feishu-cards.mjs +1 -45
- package/src/channels/feishu/feishu-runtime.mjs +10 -0
- package/src/channels/feishu/multi-bot-controller.mjs +12 -0
- package/src/channels/feishu/slash-command-panel.mjs +2 -5
- package/src/channels/qq/qq-bridge.mjs +1 -0
- package/src/channels/shared/AGENTS.md +19 -0
- package/src/channels/shared/bot-workspace-store.mjs +1 -1
- package/src/channels/shared/clear-command.mjs +2 -1
- package/src/channels/shared/command-catalog.mjs +8 -5
- 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/delivery-failure-log.mjs +111 -0
- package/src/channels/shared/diagnostic-details.mjs +1 -0
- package/src/channels/shared/harness-client.mjs +16 -9
- 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 +7 -2
- package/src/channels/shared/i18n-en/shared-c.mjs +6 -2
- package/src/channels/shared/i18n-en/telegram.mjs +6 -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 +262 -0
- package/src/channels/shared/i18n-ru/shared-c.mjs +176 -0
- package/src/channels/shared/i18n-ru/slack.mjs +22 -0
- package/src/channels/shared/i18n-ru/telegram.mjs +30 -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 +8 -4
- 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 +11 -0
- package/src/channels/shared/status-reaction.mjs +2 -0
- package/src/channels/shared/text-harness-bridge.mjs +205 -3
- package/src/channels/shared/thinking-cadence.mjs +36 -0
- package/src/channels/shared/workspace-command.mjs +43 -17
- package/src/channels/shared/workspace-labels.mjs +65 -0
- package/src/channels/shared/workspace-session.mjs +24 -4
- package/src/channels/telegram/config-store.mjs +34 -1
- package/src/channels/telegram/telegram-api.mjs +240 -32
- package/src/channels/telegram/telegram-bridge.mjs +62 -1
- package/src/channels/telegram/telegram-controller.mjs +29 -0
- package/src/channels/telegram/telegram-runtime.mjs +592 -179
- package/src/channels/telegram/voice.mjs +250 -0
- package/src/channels/wecom/wecom-bridge.mjs +1 -0
- package/src/channels/wecom-app/wecom-app-bridge.mjs +1 -0
- package/src/channels/weixin/weixin-bridge.mjs +1 -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);
|
|
@@ -386,12 +454,56 @@ function telegramFailure(error) {
|
|
|
386
454
|
};
|
|
387
455
|
}
|
|
388
456
|
|
|
389
|
-
function deliveryResult(presentation, providerMessageIds, deliveryOutcome = 'sent', reason) {
|
|
457
|
+
function deliveryResult(presentation, providerMessageIds, deliveryOutcome = 'sent', reason, evidence = null) {
|
|
390
458
|
return {
|
|
391
459
|
presentation,
|
|
392
460
|
providerMessageIds: [...new Set(providerMessageIds)],
|
|
393
461
|
deliveryOutcome,
|
|
394
462
|
...(reason ? { reason } : {}),
|
|
463
|
+
...(evidence ? { deliveryEvidence: { ...evidence, deliveryOutcome } } : {}),
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* What the send itself observed, kept next to the delivery result.
|
|
469
|
+
*
|
|
470
|
+
* The notice a user sees carries a reference id that used to be the only trace
|
|
471
|
+
* of an unconfirmed delivery. This record travels with the result so the same
|
|
472
|
+
* id, the attempt history and the text that never got a `message_id` can be
|
|
473
|
+
* written to the local log in one line.
|
|
474
|
+
*/
|
|
475
|
+
function deliveryEvidence({ target, parseMode, parts, error, reason = null, failedPart = null }) {
|
|
476
|
+
const attempts = Array.isArray(error?.sendAttempts) ? error.sendAttempts : [];
|
|
477
|
+
return {
|
|
478
|
+
chat_id: target?.chatId ?? null,
|
|
479
|
+
message_thread_id: Number.isInteger(target?.messageThreadId) ? target.messageThreadId : null,
|
|
480
|
+
// The Bot API request carries no `parse_mode` field: a part is either Rich
|
|
481
|
+
// Markdown or bare text, and that is what decides which path failed.
|
|
482
|
+
parse_mode: parseMode,
|
|
483
|
+
provider_reason: (typeof error?.code === 'string' && error.code) || reason || null,
|
|
484
|
+
failed_part: Number.isInteger(failedPart) ? failedPart : null,
|
|
485
|
+
attempts,
|
|
486
|
+
parts,
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** One part of an answer, keeping its text only when Telegram never confirmed it. */
|
|
491
|
+
function deliveryPart(index, text, messageId) {
|
|
492
|
+
return {
|
|
493
|
+
index,
|
|
494
|
+
length: typeof text === 'string' ? text.length : 0,
|
|
495
|
+
message_id: messageId ?? null,
|
|
496
|
+
...(messageId ? {} : { text: typeof text === 'string' ? text : '' }),
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** A plain fallback after a rejected Rich part still belongs to the same answer. */
|
|
501
|
+
function mergeEvidence(primary, fallback) {
|
|
502
|
+
if (!primary || !fallback) return fallback ?? primary ?? null;
|
|
503
|
+
return {
|
|
504
|
+
...fallback,
|
|
505
|
+
provider_reason: fallback.provider_reason ?? primary.provider_reason,
|
|
506
|
+
attempts: [...primary.attempts, ...fallback.attempts],
|
|
395
507
|
};
|
|
396
508
|
}
|
|
397
509
|
|
|
@@ -399,12 +511,15 @@ class TelegramDeliveryStream {
|
|
|
399
511
|
#update;
|
|
400
512
|
#finish;
|
|
401
513
|
#fail;
|
|
514
|
+
#onCancel;
|
|
402
515
|
#logger;
|
|
403
516
|
#providerMessageIds;
|
|
404
517
|
#closed = false;
|
|
405
518
|
#lastUpdate = null;
|
|
406
519
|
#lastBlock = null;
|
|
407
520
|
#keepalive = false;
|
|
521
|
+
#previewAnswer = true;
|
|
522
|
+
#uniqueFrames = false;
|
|
408
523
|
#previewStopped = false;
|
|
409
524
|
#chain = Promise.resolve();
|
|
410
525
|
|
|
@@ -412,14 +527,18 @@ class TelegramDeliveryStream {
|
|
|
412
527
|
update,
|
|
413
528
|
finish,
|
|
414
529
|
fail,
|
|
530
|
+
onCancel = null,
|
|
415
531
|
providerMessageIds = [],
|
|
416
532
|
presentation,
|
|
417
533
|
logger,
|
|
418
534
|
keepalive = false,
|
|
535
|
+
previewAnswer = true,
|
|
536
|
+
uniqueFrames = false,
|
|
419
537
|
}) {
|
|
420
538
|
this.#update = update;
|
|
421
539
|
this.#finish = finish;
|
|
422
540
|
this.#fail = fail;
|
|
541
|
+
this.#onCancel = onCancel;
|
|
423
542
|
this.#providerMessageIds = providerMessageIds;
|
|
424
543
|
this.presentation = presentation;
|
|
425
544
|
this.#logger = logger;
|
|
@@ -427,6 +546,19 @@ class TelegramDeliveryStream {
|
|
|
427
546
|
// keepalive refresh; editing a real placeholder message with identical
|
|
428
547
|
// content would be rejected by the platform.
|
|
429
548
|
this.#keepalive = keepalive === true;
|
|
549
|
+
// The placeholder is deleted before the answer is sent, so mirroring the
|
|
550
|
+
// answer text into it would show the same reply twice: first as a run of
|
|
551
|
+
// edits, then again as the delivered message.
|
|
552
|
+
this.#previewAnswer = previewAnswer !== false;
|
|
553
|
+
// A numbered carrier rewrites one line with a different prefix, so the
|
|
554
|
+
// identical-text shortcut would swallow every frame after the first and the
|
|
555
|
+
// reader would still watch a frozen placeholder.
|
|
556
|
+
this.#uniqueFrames = uniqueFrames === true;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** Whether answer text may be shown in the carrier before it is delivered. */
|
|
560
|
+
get previewAnswer() {
|
|
561
|
+
return this.#previewAnswer;
|
|
430
562
|
}
|
|
431
563
|
|
|
432
564
|
get providerMessageIds() {
|
|
@@ -446,6 +578,14 @@ class TelegramDeliveryStream {
|
|
|
446
578
|
return run;
|
|
447
579
|
}
|
|
448
580
|
|
|
581
|
+
/** Queue a write that originates outside update(), such as a paced frame
|
|
582
|
+
* released by a timer. It runs on the same chain as finish()/fail(), so a
|
|
583
|
+
* slow edit is awaited before finalization instead of landing after the
|
|
584
|
+
* answer. */
|
|
585
|
+
enqueue(task) {
|
|
586
|
+
return this.#enqueue(task);
|
|
587
|
+
}
|
|
588
|
+
|
|
449
589
|
// Live drafts can block the user's composer. Drain any pending draft before
|
|
450
590
|
// the regular question/approval message clears it, and keep this turn's
|
|
451
591
|
// preview stopped so late progress cannot block the answer again.
|
|
@@ -460,7 +600,7 @@ class TelegramDeliveryStream {
|
|
|
460
600
|
const block = createTextDeliveryBlock(value);
|
|
461
601
|
this.#lastBlock = block;
|
|
462
602
|
const key = `${block.format}:${block.text}`;
|
|
463
|
-
if (key === this.#lastUpdate) return undefined;
|
|
603
|
+
if (!this.#uniqueFrames && key === this.#lastUpdate) return undefined;
|
|
464
604
|
this.#lastUpdate = key;
|
|
465
605
|
try {
|
|
466
606
|
return await this.#update(block);
|
|
@@ -509,6 +649,9 @@ class TelegramDeliveryStream {
|
|
|
509
649
|
|
|
510
650
|
cancel() {
|
|
511
651
|
this.#closed = true;
|
|
652
|
+
// Carrier-specific teardown (a paced progress window still holding a frame
|
|
653
|
+
// and its timer) lives with whoever opened the stream.
|
|
654
|
+
this.#onCancel?.();
|
|
512
655
|
}
|
|
513
656
|
}
|
|
514
657
|
|
|
@@ -575,11 +718,22 @@ export class TelegramBotClient {
|
|
|
575
718
|
#api;
|
|
576
719
|
#signal;
|
|
577
720
|
#logger;
|
|
721
|
+
#thinkingNumbering;
|
|
722
|
+
#thinkingIntervalMs;
|
|
578
723
|
|
|
579
|
-
constructor({
|
|
724
|
+
constructor({
|
|
725
|
+
api,
|
|
726
|
+
signal,
|
|
727
|
+
logger = console,
|
|
728
|
+
thinkingNumbering = false,
|
|
729
|
+
thinkingIntervalSeconds = 0,
|
|
730
|
+
}) {
|
|
580
731
|
this.#api = api;
|
|
581
732
|
this.#signal = signal;
|
|
582
733
|
this.#logger = logger;
|
|
734
|
+
// Read once: the runtime restarts whenever the owner changes either value.
|
|
735
|
+
this.#thinkingNumbering = normalizeThinkingNumbering(thinkingNumbering);
|
|
736
|
+
this.#thinkingIntervalMs = normalizeThinkingIntervalSeconds(thinkingIntervalSeconds) * 1_000;
|
|
583
737
|
}
|
|
584
738
|
|
|
585
739
|
async sendText(target, text) {
|
|
@@ -687,82 +841,77 @@ export class TelegramBotClient {
|
|
|
687
841
|
});
|
|
688
842
|
}
|
|
689
843
|
|
|
690
|
-
async #sendPlain(target, text
|
|
844
|
+
async #sendPlain(target, text) {
|
|
691
845
|
const chunks = splitTelegramRegularText(text);
|
|
692
|
-
const providerMessageIds =
|
|
693
|
-
|
|
694
|
-
|
|
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) {
|
|
846
|
+
const providerMessageIds = [];
|
|
847
|
+
const parts = [];
|
|
848
|
+
for (const [index, chunk] of chunks.entries()) {
|
|
743
849
|
try {
|
|
744
850
|
const result = await this.#api.sendMessage({
|
|
745
851
|
chatId: target.chatId,
|
|
746
|
-
text:
|
|
852
|
+
text: chunk,
|
|
747
853
|
replyToMessageId: index === 0 ? target.replyToMessageId : undefined,
|
|
748
854
|
messageThreadId: target.messageThreadId,
|
|
749
855
|
signal: this.#signal,
|
|
750
856
|
});
|
|
751
857
|
const id = telegramMessageId(result);
|
|
752
858
|
if (id) providerMessageIds.push(id);
|
|
859
|
+
parts.push(deliveryPart(index, chunk, id));
|
|
753
860
|
} catch (error) {
|
|
861
|
+
parts.push(deliveryPart(index, chunk, null));
|
|
754
862
|
const failure = telegramFailure(error);
|
|
755
863
|
return deliveryResult(
|
|
756
864
|
'text-fallback',
|
|
757
865
|
providerMessageIds,
|
|
758
866
|
failure.outcome,
|
|
759
867
|
failure.reason,
|
|
868
|
+
deliveryEvidence({
|
|
869
|
+
target, parseMode: 'none', parts, error, failedPart: index,
|
|
870
|
+
}),
|
|
760
871
|
);
|
|
761
872
|
}
|
|
762
873
|
}
|
|
874
|
+
// A resolved call is not a delivered answer: without a message id the
|
|
875
|
+
// reader may still be staring at nothing, so the final answer claims only
|
|
876
|
+
// what it can prove and lets the caller report the rest.
|
|
877
|
+
if (providerMessageIds.length !== chunks.length) {
|
|
878
|
+
const unconfirmed = parts.find((part) => !part.message_id) ?? null;
|
|
879
|
+
return deliveryResult(
|
|
880
|
+
'text-fallback',
|
|
881
|
+
providerMessageIds,
|
|
882
|
+
'unknown',
|
|
883
|
+
'telegram-message-id-missing',
|
|
884
|
+
deliveryEvidence({
|
|
885
|
+
target,
|
|
886
|
+
parseMode: 'none',
|
|
887
|
+
parts,
|
|
888
|
+
reason: 'telegram-message-id-missing',
|
|
889
|
+
failedPart: unconfirmed?.index ?? null,
|
|
890
|
+
}),
|
|
891
|
+
);
|
|
892
|
+
}
|
|
763
893
|
return deliveryResult('text-fallback', providerMessageIds);
|
|
764
894
|
}
|
|
765
895
|
|
|
896
|
+
/** Drop the progress placeholder before the answer is sent so the turn ends
|
|
897
|
+
* with a notification instead of a silent edit. Best-effort: Telegram only
|
|
898
|
+
* lets a bot delete its own messages for 48 hours, and a stale placeholder
|
|
899
|
+
* must never cost the reader the answer that was already produced. */
|
|
900
|
+
async #deletePlaceholder(target, messageId) {
|
|
901
|
+
try {
|
|
902
|
+
await this.#api.deleteMessage({
|
|
903
|
+
chatId: target.chatId,
|
|
904
|
+
messageId,
|
|
905
|
+
signal: this.#signal,
|
|
906
|
+
});
|
|
907
|
+
} catch (error) {
|
|
908
|
+
this.#logger.warn?.(
|
|
909
|
+
'[dsh-im:telegram] unable to delete the processing placeholder:',
|
|
910
|
+
error,
|
|
911
|
+
);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
|
|
766
915
|
async #sendRich(target, block) {
|
|
767
916
|
if (block.format === 'plain') return this.#sendPlain(target, block.text);
|
|
768
917
|
|
|
@@ -774,6 +923,7 @@ export class TelegramBotClient {
|
|
|
774
923
|
return this.#sendPlain(target, block.text);
|
|
775
924
|
}
|
|
776
925
|
const providerMessageIds = [];
|
|
926
|
+
const parts = [];
|
|
777
927
|
for (const [index, chunk] of chunks.entries()) {
|
|
778
928
|
try {
|
|
779
929
|
const result = await this.#api.sendRichMessage({
|
|
@@ -785,14 +935,20 @@ export class TelegramBotClient {
|
|
|
785
935
|
});
|
|
786
936
|
const id = telegramMessageId(result);
|
|
787
937
|
if (id) providerMessageIds.push(id);
|
|
938
|
+
parts.push(deliveryPart(index, chunk.source ?? chunk.markdown, id));
|
|
788
939
|
} catch (error) {
|
|
940
|
+
parts.push(deliveryPart(index, chunk.source ?? chunk.markdown, null));
|
|
789
941
|
const failure = telegramFailure(error);
|
|
942
|
+
const evidence = deliveryEvidence({
|
|
943
|
+
target, parseMode: 'rich_markdown', parts, error, failedPart: index,
|
|
944
|
+
});
|
|
790
945
|
if (failure.outcome === 'unknown') {
|
|
791
946
|
return deliveryResult(
|
|
792
947
|
'telegram-rich-final',
|
|
793
948
|
providerMessageIds,
|
|
794
949
|
'unknown',
|
|
795
950
|
failure.reason,
|
|
951
|
+
evidence,
|
|
796
952
|
);
|
|
797
953
|
}
|
|
798
954
|
const remaining = chunks.slice(index).map((part) => part.source).join('');
|
|
@@ -800,85 +956,36 @@ export class TelegramBotClient {
|
|
|
800
956
|
...target,
|
|
801
957
|
replyToMessageId: index === 0 ? target.replyToMessageId : undefined,
|
|
802
958
|
}, remaining);
|
|
959
|
+
// A successful fallback is a delivered answer; only an unconfirmed one
|
|
960
|
+
// needs the Rich rejection in the log as well.
|
|
803
961
|
return deliveryResult(
|
|
804
962
|
fallback.presentation,
|
|
805
963
|
[...providerMessageIds, ...fallback.providerMessageIds],
|
|
806
964
|
fallback.deliveryOutcome,
|
|
807
965
|
fallback.reason,
|
|
966
|
+
fallback.deliveryOutcome === 'sent'
|
|
967
|
+
? null
|
|
968
|
+
: mergeEvidence(evidence, fallback.deliveryEvidence),
|
|
808
969
|
);
|
|
809
970
|
}
|
|
810
971
|
}
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
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
|
-
}
|
|
972
|
+
// Same proof as the plain path: a rich send that never returned an id
|
|
973
|
+
// cannot be reported as delivered.
|
|
974
|
+
if (providerMessageIds.length !== chunks.length) {
|
|
975
|
+
const unconfirmed = parts.find((part) => !part.message_id) ?? null;
|
|
976
|
+
return deliveryResult(
|
|
977
|
+
'telegram-rich-final',
|
|
978
|
+
providerMessageIds,
|
|
979
|
+
'unknown',
|
|
980
|
+
'telegram-message-id-missing',
|
|
981
|
+
deliveryEvidence({
|
|
982
|
+
target,
|
|
983
|
+
parseMode: 'rich_markdown',
|
|
984
|
+
parts,
|
|
985
|
+
reason: 'telegram-message-id-missing',
|
|
986
|
+
failedPart: unconfirmed?.index ?? null,
|
|
987
|
+
}),
|
|
988
|
+
);
|
|
882
989
|
}
|
|
883
990
|
return deliveryResult('telegram-rich-final', providerMessageIds);
|
|
884
991
|
}
|
|
@@ -901,33 +1008,120 @@ export class TelegramBotClient {
|
|
|
901
1008
|
if (!Number.isSafeInteger(messageId)) {
|
|
902
1009
|
throw new Error('Telegram did not return a placeholder message id');
|
|
903
1010
|
}
|
|
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
|
-
}
|
|
1011
|
+
const editBlock = async (block) => {
|
|
1012
|
+
if (block.format === 'plain') {
|
|
915
1013
|
await this.#api.editMessageText({
|
|
916
1014
|
chatId: target.chatId,
|
|
917
1015
|
messageId,
|
|
918
|
-
|
|
1016
|
+
text: block.text,
|
|
919
1017
|
signal: this.#signal,
|
|
920
1018
|
});
|
|
921
|
-
return deliveryResult('
|
|
1019
|
+
return deliveryResult('text-fallback', [String(messageId)]);
|
|
1020
|
+
}
|
|
1021
|
+
await this.#api.editMessageText({
|
|
1022
|
+
chatId: target.chatId,
|
|
1023
|
+
messageId,
|
|
1024
|
+
richMessage: { markdown: toTelegramRichMarkdown(block.text) },
|
|
1025
|
+
signal: this.#signal,
|
|
1026
|
+
});
|
|
1027
|
+
return deliveryResult('telegram-rich-draft', [String(messageId)]);
|
|
1028
|
+
};
|
|
1029
|
+
// One message rewritten in place means a row of identical "Using bash"
|
|
1030
|
+
// edits looks frozen. Numbering counts every progress frame of the turn and
|
|
1031
|
+
// prefixes it, so the line keeps moving; pacing keeps the edits themselves
|
|
1032
|
+
// rare and still lands the newest held frame when its window closes.
|
|
1033
|
+
const numbering = this.#thinkingNumbering;
|
|
1034
|
+
const intervalMs = this.#thinkingIntervalMs;
|
|
1035
|
+
let sequence = 0;
|
|
1036
|
+
let held = null;
|
|
1037
|
+
let windowTimer = null;
|
|
1038
|
+
let windowEndsAt = 0;
|
|
1039
|
+
let closed = false;
|
|
1040
|
+
let stream = null;
|
|
1041
|
+
const clearWindowTimer = () => {
|
|
1042
|
+
if (windowTimer === null) return;
|
|
1043
|
+
clearTimeout(windowTimer);
|
|
1044
|
+
windowTimer = null;
|
|
1045
|
+
};
|
|
1046
|
+
const sendHeld = async () => {
|
|
1047
|
+
const frame = held;
|
|
1048
|
+
held = null;
|
|
1049
|
+
if (!frame || closed) return;
|
|
1050
|
+
try {
|
|
1051
|
+
await editBlock(frame);
|
|
1052
|
+
} catch (error) {
|
|
1053
|
+
this.#logger?.warn?.('[dsh-im:telegram] placeholder frame failed:', error);
|
|
1054
|
+
}
|
|
1055
|
+
};
|
|
1056
|
+
const armWindowTimer = () => {
|
|
1057
|
+
if (windowTimer !== null) return;
|
|
1058
|
+
windowTimer = setTimeout(() => {
|
|
1059
|
+
windowTimer = null;
|
|
1060
|
+
windowEndsAt = Date.now() + intervalMs;
|
|
1061
|
+
// The released frame enters the stream's queue instead of editing on its
|
|
1062
|
+
// own: an unqueued edit could still be in flight while finish() deletes
|
|
1063
|
+
// the placeholder and sends the answer, so the stale frame would land
|
|
1064
|
+
// after the reply.
|
|
1065
|
+
void stream.enqueue(() => sendHeld());
|
|
1066
|
+
}, Math.max(0, windowEndsAt - Date.now()));
|
|
1067
|
+
};
|
|
1068
|
+
// Finalization takes whatever the window still holds: the last frame goes
|
|
1069
|
+
// out before the answer, and nothing may start after it.
|
|
1070
|
+
const drainHeld = async () => {
|
|
1071
|
+
clearWindowTimer();
|
|
1072
|
+
await sendHeld();
|
|
1073
|
+
closed = true;
|
|
1074
|
+
};
|
|
1075
|
+
const pushProgress = async (block) => {
|
|
1076
|
+
if (closed) return undefined;
|
|
1077
|
+
sequence += 1;
|
|
1078
|
+
const framed = numbering && block.text
|
|
1079
|
+
? { ...block, text: `${sequence}. ${block.text}` }
|
|
1080
|
+
: block;
|
|
1081
|
+
if (intervalMs <= 0) return editBlock(framed);
|
|
1082
|
+
if (Date.now() >= windowEndsAt) {
|
|
1083
|
+
// The deadline has passed but its timer may not have run yet, and that
|
|
1084
|
+
// callback would release the frame this newer one supersedes. Drop both
|
|
1085
|
+
// the held frame and its timer before letting the new frame through.
|
|
1086
|
+
clearWindowTimer();
|
|
1087
|
+
windowEndsAt = Date.now() + intervalMs;
|
|
1088
|
+
held = null;
|
|
1089
|
+
return editBlock(framed);
|
|
1090
|
+
}
|
|
1091
|
+
held = framed;
|
|
1092
|
+
armWindowTimer();
|
|
1093
|
+
return undefined;
|
|
1094
|
+
};
|
|
1095
|
+
stream = new TelegramDeliveryStream({
|
|
1096
|
+
update: (block) => pushProgress(block),
|
|
1097
|
+
// The placeholder carries progress only: its last frame would be a silent
|
|
1098
|
+
// edit, so the answer goes out as its own message and Telegram notifies
|
|
1099
|
+
// the reader that the turn is over.
|
|
1100
|
+
finish: async (block) => {
|
|
1101
|
+
await drainHeld();
|
|
1102
|
+
await this.#deletePlaceholder(target, messageId);
|
|
1103
|
+
return this.#sendRich(target, block);
|
|
1104
|
+
},
|
|
1105
|
+
fail: async (block) => {
|
|
1106
|
+
await drainHeld();
|
|
1107
|
+
await this.#deletePlaceholder(target, messageId);
|
|
1108
|
+
return this.#sendPlain(target, block.text);
|
|
1109
|
+
},
|
|
1110
|
+
// A cancelled turn must not wake up later and rewrite the placeholder the
|
|
1111
|
+
// reader has already stopped watching.
|
|
1112
|
+
onCancel: () => {
|
|
1113
|
+
closed = true;
|
|
1114
|
+
clearWindowTimer();
|
|
1115
|
+
held = null;
|
|
922
1116
|
},
|
|
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
1117
|
presentation: 'telegram-regular',
|
|
1118
|
+
// Answer text is not mirrored into the placeholder: it is deleted before
|
|
1119
|
+
// the real message goes out, so a preview would duplicate the reply.
|
|
1120
|
+
previewAnswer: false,
|
|
1121
|
+
uniqueFrames: numbering,
|
|
929
1122
|
logger: this.#logger,
|
|
930
1123
|
});
|
|
1124
|
+
return stream;
|
|
931
1125
|
}
|
|
932
1126
|
|
|
933
1127
|
async openStream(target) {
|
|
@@ -971,6 +1165,14 @@ export class TelegramBotClient {
|
|
|
971
1165
|
const providerMessageIds = [];
|
|
972
1166
|
let firstMessageId = null;
|
|
973
1167
|
let closed = false;
|
|
1168
|
+
// Numbering counts every frame of the turn, paced-away ones included, so the
|
|
1169
|
+
// gaps in the visible numbers tell how much was held back.
|
|
1170
|
+
const numbering = this.#thinkingNumbering;
|
|
1171
|
+
const intervalMs = this.#thinkingIntervalMs;
|
|
1172
|
+
let sequence = 0;
|
|
1173
|
+
let held = null;
|
|
1174
|
+
let windowTimer = null;
|
|
1175
|
+
let windowEndsAt = 0;
|
|
974
1176
|
const logger = this.#logger;
|
|
975
1177
|
const warnFailure = (label, error) => {
|
|
976
1178
|
logger?.warn?.(`[dsh-im:telegram] thinking stream ${label} failed:`, error);
|
|
@@ -989,6 +1191,66 @@ export class TelegramBotClient {
|
|
|
989
1191
|
providerMessageIds.push(String(id));
|
|
990
1192
|
}
|
|
991
1193
|
};
|
|
1194
|
+
const deliver = async (label, text) => {
|
|
1195
|
+
try {
|
|
1196
|
+
await sendLine(text);
|
|
1197
|
+
} catch (error) {
|
|
1198
|
+
warnFailure(label, error);
|
|
1199
|
+
}
|
|
1200
|
+
};
|
|
1201
|
+
// Trace sends run in the background: the window timer starts one and nobody
|
|
1202
|
+
// awaits it, so finish() would otherwise find an empty buffer and let the
|
|
1203
|
+
// answer overtake a trace request that is still on the wire.
|
|
1204
|
+
const inFlight = new Set();
|
|
1205
|
+
const track = (label, text) => {
|
|
1206
|
+
const send = deliver(label, text).finally(() => { inFlight.delete(send); });
|
|
1207
|
+
inFlight.add(send);
|
|
1208
|
+
return send;
|
|
1209
|
+
};
|
|
1210
|
+
// Settling one send can release another (a held frame), so drain in a loop.
|
|
1211
|
+
const settleInFlight = async () => {
|
|
1212
|
+
while (inFlight.size > 0) await Promise.all([...inFlight]);
|
|
1213
|
+
};
|
|
1214
|
+
const clearWindowTimer = () => {
|
|
1215
|
+
if (windowTimer === null) return;
|
|
1216
|
+
clearTimeout(windowTimer);
|
|
1217
|
+
windowTimer = null;
|
|
1218
|
+
};
|
|
1219
|
+
const sendHeld = () => {
|
|
1220
|
+
const frame = held;
|
|
1221
|
+
held = null;
|
|
1222
|
+
return frame ? track(frame.label, frame.text) : Promise.resolve();
|
|
1223
|
+
};
|
|
1224
|
+
const armWindowTimer = () => {
|
|
1225
|
+
if (windowTimer !== null) return;
|
|
1226
|
+
windowTimer = setTimeout(() => {
|
|
1227
|
+
windowTimer = null;
|
|
1228
|
+
windowEndsAt = Date.now() + intervalMs;
|
|
1229
|
+
// The window keeps only the newest frame, so a burst collapses to one
|
|
1230
|
+
// message instead of a queue of frames nobody wants to read.
|
|
1231
|
+
void sendHeld();
|
|
1232
|
+
}, Math.max(0, windowEndsAt - Date.now()));
|
|
1233
|
+
};
|
|
1234
|
+
/** One frame: immediate outside a window, otherwise the newest held one. */
|
|
1235
|
+
const emit = (label, text) => {
|
|
1236
|
+
if (closed) return Promise.resolve();
|
|
1237
|
+
sequence += 1;
|
|
1238
|
+
const frame = { label, text: numbering ? `${sequence} ${text}` : text };
|
|
1239
|
+
if (intervalMs <= 0) return track(frame.label, frame.text);
|
|
1240
|
+
if (Date.now() >= windowEndsAt) {
|
|
1241
|
+
// The deadline has passed but its timer may not have run yet, and that
|
|
1242
|
+
// callback would deliver the frame this newer one supersedes. Drop both
|
|
1243
|
+
// the held frame and its timer before letting the new frame through.
|
|
1244
|
+
clearWindowTimer();
|
|
1245
|
+
held = null;
|
|
1246
|
+
windowEndsAt = Date.now() + intervalMs;
|
|
1247
|
+
return track(frame.label, frame.text);
|
|
1248
|
+
}
|
|
1249
|
+
// Inside the window: replace whatever waited, never append.
|
|
1250
|
+
held = frame;
|
|
1251
|
+
armWindowTimer();
|
|
1252
|
+
return Promise.resolve();
|
|
1253
|
+
};
|
|
992
1254
|
return {
|
|
993
1255
|
get messageId() {
|
|
994
1256
|
return firstMessageId;
|
|
@@ -1003,27 +1265,21 @@ export class TelegramBotClient {
|
|
|
1003
1265
|
update: async () => {},
|
|
1004
1266
|
refresh: async () => {},
|
|
1005
1267
|
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;
|
|
1268
|
+
sendToolTrace: (name, argumentsValue) => emit('tool trace', formatToolTrace(name, argumentsValue)),
|
|
1269
|
+
sendThinking: (text) => {
|
|
1016
1270
|
const line = formatThinkingLine(text);
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
await sendLine(line);
|
|
1020
|
-
} catch (error) {
|
|
1021
|
-
warnFailure('thinking line', error);
|
|
1022
|
-
}
|
|
1023
|
-
})(),
|
|
1271
|
+
return line ? emit('thinking line', line) : Promise.resolve();
|
|
1272
|
+
},
|
|
1024
1273
|
async finish(answer) {
|
|
1025
1274
|
if (closed) throw new Error('Message stream is already closed');
|
|
1026
1275
|
closed = true;
|
|
1276
|
+
// The held frame is the last thing the turn thought about, so it goes
|
|
1277
|
+
// out before the answer instead of after its own result. Then wait for
|
|
1278
|
+
// every trace still in flight, so none can land behind the answer; the
|
|
1279
|
+
// trace sends are already best-effort and never reject.
|
|
1280
|
+
clearWindowTimer();
|
|
1281
|
+
await sendHeld();
|
|
1282
|
+
await settleInFlight();
|
|
1027
1283
|
const format = answer && typeof answer === 'object' && answer.format === 'markdown'
|
|
1028
1284
|
? 'markdown'
|
|
1029
1285
|
: 'plain';
|
|
@@ -1067,14 +1323,18 @@ export class TelegramBotClient {
|
|
|
1067
1323
|
if (result?.deliveryOutcome === 'unknown') {
|
|
1068
1324
|
// 结果未知(超时等):可能已送达,重发会造成重复,保留 unknown 状态。
|
|
1069
1325
|
remember(result.providerMessageIds);
|
|
1070
|
-
return deliveryResult(
|
|
1326
|
+
return deliveryResult(
|
|
1327
|
+
'telegram-thinking', providerMessageIds, 'unknown', result.reason, result.deliveryEvidence,
|
|
1328
|
+
);
|
|
1071
1329
|
}
|
|
1072
1330
|
// 明确失败:该分片确认未送达。纯文本分片再走一次 plain 重发
|
|
1073
1331
|
// (markdown 分片的 plain 回退已在 #sendRich 内尝试过),只重发
|
|
1074
1332
|
// 尚未发送的尾部内容,已成功的分片不重复。
|
|
1075
1333
|
remember(result?.providerMessageIds);
|
|
1076
1334
|
if (format === 'markdown') {
|
|
1077
|
-
return deliveryResult(
|
|
1335
|
+
return deliveryResult(
|
|
1336
|
+
'telegram-thinking', providerMessageIds, 'failed', result.reason, result.deliveryEvidence,
|
|
1337
|
+
);
|
|
1078
1338
|
}
|
|
1079
1339
|
warnFailure('final answer chunk', new Error('chunk definitively rejected'));
|
|
1080
1340
|
try {
|
|
@@ -1092,6 +1352,9 @@ export class TelegramBotClient {
|
|
|
1092
1352
|
},
|
|
1093
1353
|
cancel() {
|
|
1094
1354
|
closed = true;
|
|
1355
|
+
// A cancelled turn must not leave a timer that sends a stale frame.
|
|
1356
|
+
clearWindowTimer();
|
|
1357
|
+
held = null;
|
|
1095
1358
|
},
|
|
1096
1359
|
};
|
|
1097
1360
|
}
|
|
@@ -1119,6 +1382,11 @@ export class TelegramRuntime {
|
|
|
1119
1382
|
#groupHistory;
|
|
1120
1383
|
#groupTriggers;
|
|
1121
1384
|
#accessPolicy;
|
|
1385
|
+
#voice;
|
|
1386
|
+
#voiceTimeoutMs;
|
|
1387
|
+
#conversationQueue;
|
|
1388
|
+
/** Reasons already reported, so a broken recognizer logs once. */
|
|
1389
|
+
#voiceFailures = new Set();
|
|
1122
1390
|
#logger;
|
|
1123
1391
|
#diagnostics;
|
|
1124
1392
|
#replyTimeoutMs;
|
|
@@ -1149,6 +1417,8 @@ export class TelegramRuntime {
|
|
|
1149
1417
|
contextEnhancement,
|
|
1150
1418
|
groupHistory,
|
|
1151
1419
|
accessPolicy,
|
|
1420
|
+
voice = null,
|
|
1421
|
+
voiceTimeoutMs = 60_000,
|
|
1152
1422
|
logger = console,
|
|
1153
1423
|
replyTimeoutMs = 600_000,
|
|
1154
1424
|
createApi = (options) => new TelegramApi(options),
|
|
@@ -1168,6 +1438,16 @@ export class TelegramRuntime {
|
|
|
1168
1438
|
// normalized snapshot is read once per start.
|
|
1169
1439
|
this.#groupTriggers = normalizeGroupTriggers(config.groupTriggers);
|
|
1170
1440
|
this.#accessPolicy = accessPolicy;
|
|
1441
|
+
// null when the Host mounts no speech service; voice messages then stay textless.
|
|
1442
|
+
this.#voice = voice;
|
|
1443
|
+
this.#voiceTimeoutMs = voiceTimeoutMs;
|
|
1444
|
+
// Voice prep and delivery are serialised per conversation, never per poll.
|
|
1445
|
+
this.#conversationQueue = createConversationQueue({
|
|
1446
|
+
onError: (error, key) => this.#logger.error?.(
|
|
1447
|
+
`[dsh-im:telegram] bot ${this.#config.botId} queued work failed for ${key}:`,
|
|
1448
|
+
error?.message ?? error,
|
|
1449
|
+
),
|
|
1450
|
+
});
|
|
1171
1451
|
this.#logger = logger; this.#diagnostics = createConnectionDiagnostics({ channel: 'telegram', logger });
|
|
1172
1452
|
this.#replyTimeoutMs = replyTimeoutMs;
|
|
1173
1453
|
this.#createApi = createApi;
|
|
@@ -1249,6 +1529,10 @@ export class TelegramRuntime {
|
|
|
1249
1529
|
token: this.#token,
|
|
1250
1530
|
fetchImpl: transport.fetchImpl,
|
|
1251
1531
|
FormDataImpl: transport.FormDataImpl,
|
|
1532
|
+
// Telegram budgets new messages per chat; the bot waits for a free slot
|
|
1533
|
+
// instead of dropping the message, and retries after a 429.
|
|
1534
|
+
sendLimitPerMinute: normalizeSendLimitPerMinute(this.#config?.sendLimitPerMinute),
|
|
1535
|
+
logger: this.#logger,
|
|
1252
1536
|
});
|
|
1253
1537
|
this.#api = api;
|
|
1254
1538
|
const bot = await api.getMe({ signal: controller.signal });
|
|
@@ -1274,6 +1558,9 @@ export class TelegramRuntime {
|
|
|
1274
1558
|
api,
|
|
1275
1559
|
signal: controller.signal,
|
|
1276
1560
|
logger: this.#logger,
|
|
1561
|
+
// Trace frames are numbered and paced per bot; 0 seconds means no pacing.
|
|
1562
|
+
thinkingNumbering: this.#config?.thinkingNumbering,
|
|
1563
|
+
thinkingIntervalSeconds: this.#config?.thinkingIntervalSeconds,
|
|
1277
1564
|
});
|
|
1278
1565
|
this.#bridge = new TelegramHarnessBridge({
|
|
1279
1566
|
bot: client,
|
|
@@ -1315,6 +1602,7 @@ export class TelegramRuntime {
|
|
|
1315
1602
|
);
|
|
1316
1603
|
}
|
|
1317
1604
|
}
|
|
1605
|
+
await this.#replayPendingVoice(controller.signal);
|
|
1318
1606
|
this.#pollTask = this.#poll(cursor, controller.signal);
|
|
1319
1607
|
this.#pollTask.catch((error) => {
|
|
1320
1608
|
if (controller.signal.aborted) return;
|
|
@@ -1380,6 +1668,132 @@ export class TelegramRuntime {
|
|
|
1380
1668
|
}
|
|
1381
1669
|
}
|
|
1382
1670
|
|
|
1671
|
+
/**
|
|
1672
|
+
* Queue one update: durable pending record first, then per-conversation work.
|
|
1673
|
+
*
|
|
1674
|
+
* Ordering inside a chat is kept, while other chats, callbacks and the cursor
|
|
1675
|
+
* keep moving. The pending entry is removed only once the bridge owns the
|
|
1676
|
+
* message, so a restart before that point can replay it.
|
|
1677
|
+
*/
|
|
1678
|
+
async #dispatchUpdate(update, message, contextSnapshot, signal) {
|
|
1679
|
+
const needsPreparation = Boolean(message.voice) && message.addressed === true
|
|
1680
|
+
&& !message.content.trim();
|
|
1681
|
+
const pendingId = `telegram-voice:${update.update_id}`;
|
|
1682
|
+
if (needsPreparation) {
|
|
1683
|
+
try {
|
|
1684
|
+
await this.#state.putPendingMessage({
|
|
1685
|
+
id: pendingId,
|
|
1686
|
+
key: message.conversationId,
|
|
1687
|
+
messageId: String(message.messageId),
|
|
1688
|
+
kind: message.kind,
|
|
1689
|
+
text: voiceNote({ voice: message.voice, reason: 'transcription pending' }),
|
|
1690
|
+
senderId: String(message.senderId),
|
|
1691
|
+
target: { voiceReplay: { update, contextSnapshot } },
|
|
1692
|
+
});
|
|
1693
|
+
} catch (error) {
|
|
1694
|
+
this.#logger.warn?.(
|
|
1695
|
+
`[dsh-im:telegram] bot ${this.#config.botId} could not persist a queued voice message:`,
|
|
1696
|
+
error?.message ?? error,
|
|
1697
|
+
);
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
let accepted = false;
|
|
1701
|
+
void this.#conversationQueue.run(message.conversationId, async () => {
|
|
1702
|
+
try {
|
|
1703
|
+
if (signal.aborted) return;
|
|
1704
|
+
if (needsPreparation) await this.#transcribeVoice(message, signal);
|
|
1705
|
+
if (signal.aborted) return;
|
|
1706
|
+
await captureGroupHistory(this.#groupHistory, message, groupHistoryEntry('telegram', update, message), {
|
|
1707
|
+
logger: this.#logger,
|
|
1708
|
+
});
|
|
1709
|
+
accepted = true;
|
|
1710
|
+
// The bridge owns turn ordering; awaiting it here would park the
|
|
1711
|
+
// conversation behind a turn that waits for the user.
|
|
1712
|
+
void this.#bridge.accept(message, { contextSnapshot }).catch((error) => {
|
|
1713
|
+
if (signal.aborted) return;
|
|
1714
|
+
this.#logger.error?.(
|
|
1715
|
+
`[dsh-im:telegram] bot ${this.#config.botId} message handling failed:`,
|
|
1716
|
+
extractConnectionEvidence(error).details,
|
|
1717
|
+
);
|
|
1718
|
+
});
|
|
1719
|
+
} finally {
|
|
1720
|
+
// A cancelled prepare keeps the record: the next start replays it.
|
|
1721
|
+
if (needsPreparation && accepted) {
|
|
1722
|
+
await this.#state.removePendingMessage(pendingId).catch(() => {});
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
});
|
|
1726
|
+
}
|
|
1727
|
+
|
|
1728
|
+
/**
|
|
1729
|
+
* Replay voice messages whose preparation was interrupted by a restart.
|
|
1730
|
+
*
|
|
1731
|
+
* The raw update travels with the pending record, so the message is rebuilt
|
|
1732
|
+
* exactly as the poller first saw it.
|
|
1733
|
+
*/
|
|
1734
|
+
async #replayPendingVoice(signal) {
|
|
1735
|
+
let entries = [];
|
|
1736
|
+
try {
|
|
1737
|
+
entries = typeof this.#state.pendingMessages === 'function' ? this.#state.pendingMessages() : [];
|
|
1738
|
+
} catch {
|
|
1739
|
+
return;
|
|
1740
|
+
}
|
|
1741
|
+
for (const entry of entries) {
|
|
1742
|
+
const replayed = entry?.target?.voiceReplay;
|
|
1743
|
+
if (!replayed || !replayed.update) continue;
|
|
1744
|
+
if (signal.aborted) return;
|
|
1745
|
+
const message = normalizeTelegramUpdate(replayed.update, {
|
|
1746
|
+
botId: this.#config.platformId,
|
|
1747
|
+
username: this.#config.username,
|
|
1748
|
+
// Same rules the poller applied: a replayed group update must keep the
|
|
1749
|
+
// addressing decision that queued it.
|
|
1750
|
+
groupTriggers: this.#groupTriggers,
|
|
1751
|
+
loadFile: (fileId, options) => this.#api.downloadFile({ fileId, ...options }),
|
|
1752
|
+
loadFileStream: (fileId, options) => this.#api.downloadFileStream({ fileId, ...options }),
|
|
1753
|
+
loadReplyContent: (reference, options) => this.#loadReplyContent(reference, options),
|
|
1754
|
+
});
|
|
1755
|
+
if (!message) {
|
|
1756
|
+
await this.#state.removePendingMessage(entry.id).catch(() => {});
|
|
1757
|
+
continue;
|
|
1758
|
+
}
|
|
1759
|
+
this.#logger.warn?.(
|
|
1760
|
+
`[dsh-im:telegram] bot ${this.#config.botId} replaying an interrupted voice message`,
|
|
1761
|
+
);
|
|
1762
|
+
await this.#dispatchUpdate(replayed.update, message, replayed.contextSnapshot, signal);
|
|
1763
|
+
}
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
/**
|
|
1767
|
+
* Substitute a transcript — or an explicit "not transcribed" note — for an
|
|
1768
|
+
* empty voice message.
|
|
1769
|
+
*
|
|
1770
|
+
* The note is the model's input, not the user's answer: the channel never
|
|
1771
|
+
* phrases a reply on its own, and the note says plainly that no transcript
|
|
1772
|
+
* exists so nothing is invented from the audio.
|
|
1773
|
+
*/
|
|
1774
|
+
async #transcribeVoice(message, signal) {
|
|
1775
|
+
if (!voiceMessageAllowed(this.#accessPolicy, message)) return;
|
|
1776
|
+
await fillVoiceContent({
|
|
1777
|
+
message,
|
|
1778
|
+
voice: message.voice,
|
|
1779
|
+
api: this.#api,
|
|
1780
|
+
transcriber: this.#voice,
|
|
1781
|
+
timeoutMs: this.#voiceTimeoutMs,
|
|
1782
|
+
signal,
|
|
1783
|
+
logFailure: (reason, error) => this.#logVoiceFailure(reason, error),
|
|
1784
|
+
});
|
|
1785
|
+
}
|
|
1786
|
+
|
|
1787
|
+
/** Report one reason per runtime start; the model still gets a note every time. */
|
|
1788
|
+
#logVoiceFailure(reason, error) {
|
|
1789
|
+
if (this.#voiceFailures.has(reason)) return;
|
|
1790
|
+
this.#voiceFailures.add(reason);
|
|
1791
|
+
this.#logger.warn?.(
|
|
1792
|
+
`[dsh-im:telegram] bot ${this.#config.botId} voice transcription unavailable: ${reason}`,
|
|
1793
|
+
error?.message ?? '',
|
|
1794
|
+
);
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1383
1797
|
async #loadReplyContent(reference, { signal } = {}) {
|
|
1384
1798
|
const key = typeof reference?.conversationKey === 'string'
|
|
1385
1799
|
? reference.conversationKey.trim() : '';
|
|
@@ -1441,16 +1855,9 @@ export class TelegramRuntime {
|
|
|
1441
1855
|
loadReplyContent: (reference, options) => this.#loadReplyContent(reference, options),
|
|
1442
1856
|
});
|
|
1443
1857
|
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
|
-
});
|
|
1858
|
+
// The queued record is written before the caller persists the cursor,
|
|
1859
|
+
// so a restart replays preparation instead of losing the update.
|
|
1860
|
+
await this.#dispatchUpdate(update, message, contextSnapshot, signal);
|
|
1454
1861
|
}
|
|
1455
1862
|
cursor = update.update_id + 1;
|
|
1456
1863
|
await this.#state.setCursor(cursor);
|
|
@@ -1460,6 +1867,7 @@ export class TelegramRuntime {
|
|
|
1460
1867
|
|
|
1461
1868
|
async stop() {
|
|
1462
1869
|
const pollTask = this.#pollTask;
|
|
1870
|
+
const queued = this.#conversationQueue.idle();
|
|
1463
1871
|
const bridge = this.#bridge;
|
|
1464
1872
|
const httpTransport = this.#httpTransport;
|
|
1465
1873
|
this.#abortController?.abort();
|
|
@@ -1472,6 +1880,11 @@ export class TelegramRuntime {
|
|
|
1472
1880
|
pollTask?.catch(() => undefined) ?? Promise.resolve(),
|
|
1473
1881
|
new Promise((resolve) => setTimeout(resolve, 2_000)),
|
|
1474
1882
|
]);
|
|
1883
|
+
// Queued per-conversation work settles on its own deadline, never shutdown.
|
|
1884
|
+
await Promise.race([
|
|
1885
|
+
queued,
|
|
1886
|
+
new Promise((resolve) => setTimeout(resolve, 2_000)),
|
|
1887
|
+
]);
|
|
1475
1888
|
await Promise.race([
|
|
1476
1889
|
bridge?.waitForIdle() ?? Promise.resolve(),
|
|
1477
1890
|
new Promise((resolve) => setTimeout(resolve, 2_000)),
|