dsh-tg-bridge 1.10.0 → 1.10.1

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.
Files changed (2) hide show
  1. package/bridge.mjs +15 -137
  2. package/package.json +1 -1
package/bridge.mjs CHANGED
@@ -28,6 +28,7 @@ import { writeSteerJob } from './steer-queue.mjs';
28
28
  import { inlineText } from './media-text.mjs';
29
29
  import { createAlbumBuffer } from './albums.mjs';
30
30
  import { turnArgs } from './cli-args.mjs';
31
+ import { chunk, markdownParts, toPlainText, toTelegramHtml } from './format.mjs';
31
32
  import { ensureProfile } from './profiles.mjs';
32
33
  import { handleControl, CONTROL_COMMANDS, modelOf, reasoningOf } from './control.mjs';
33
34
  import { drainGoalJobs, goalOf, renderPromptBlock } from './goals.mjs';
@@ -379,24 +380,6 @@ async function tg(method, body, timeoutMs = 60000, attempts = 3) {
379
380
  throw lastError;
380
381
  }
381
382
 
382
- function chunk(text, size = 4000) {
383
- const out = [];
384
- let rest = text;
385
- while (rest.length > size) {
386
- let cut = rest.lastIndexOf('\n', size);
387
- if (cut < size * 0.5) cut = size;
388
- out.push(rest.slice(0, cut));
389
- rest = rest.slice(cut).replace(/^\n+/, '');
390
- }
391
- if (rest.length) out.push(rest);
392
- return out;
393
- }
394
-
395
- /**
396
- * Forum topic id of a message, or 0 for the General topic and for private chats.
397
- * Telegram omits `message_thread_id` for the General topic of a forum, so 0 is
398
- * the "no topic" marker and must never be sent back as a thread id.
399
- */
400
383
  function threadOf(msg) {
401
384
  const id = msg.message_thread_id ?? msg.reply_to_message?.message_thread_id;
402
385
  return Number.isInteger(id) && id > 0 ? id : 0;
@@ -591,126 +574,18 @@ function immediateCommandOf(text) {
591
574
  return immediateKind(collapsed, rest);
592
575
  }
593
576
 
594
- /**
595
- * Turn model markdown into plain readable text.
596
- *
597
- * The bridge sends without `parse_mode`, so every `**bold**`, `### heading` and
598
- * `` `code` `` reached the person as literal punctuation — the chat looked
599
- * "filled with junk". Telegram formatting is opt-in per message and a bad
600
- * entity rejects the whole send, so the safe direction is to strip the markers
601
- * and keep the words.
602
- */
603
- export function toPlainText(input) {
604
- let text = String(input ?? '');
605
- // Fenced code blocks: keep the body, drop the fence and language tag.
606
- text = text.replace(/```[a-zA-Z0-9]*\n?/g, '').replace(/```/g, '');
607
- // Inline code and bold/italic/strike markers.
608
- text = text.replace(/`([^`]*)`/g, '$1');
609
- text = text.replace(/\*\*\*([^*]+)\*\*\*/g, '$1');
610
- text = text.replace(/\*\*([^*]+)\*\*/g, '$1');
611
- text = text.replace(/(^|[\s(])\*([^*\n]+)\*(?=[\s).,!?:;]|$)/g, '$1$2');
612
- text = text.replace(/__([^_]+)__/g, '$1');
613
- text = text.replace(/(^|[\s(])_([^_\n]+)_(?=[\s).,!?:;]|$)/g, '$1$2');
614
- text = text.replace(/~~([^~]+)~~/g, '$1');
615
- // Headings: "### Title" -> "Title".
616
- text = text.replace(/^\s{0,3}#{1,6}\s+/gm, '');
617
- // Links: [label](url) -> label (url); bare <url> stays as is.
618
- text = text.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '$1 ($2)');
619
- // Blockquote markers at line start.
620
- text = text.replace(/^\s{0,3}>\s?/gm, '');
621
- // Bullets keep a dash, but " - x" indentation is dropped to one level.
622
- text = text.replace(/^\s*[-*+]\s+/gm, '— ');
623
- // Tables: drop the separator row first (it is pure punctuation), then turn
624
- // the remaining rows into one line each with " · " between cells. The
625
- // separator pattern uses [ \t] rather than \s so it cannot eat the newline
626
- // and glue neighbouring rows together.
627
- text = text.replace(/^[ \t]*\|?[ \t:|-]*-[ \t:|-]*\|?[ \t]*$/gm, '');
628
- text = text.replace(/^[ \t]*\|(.+)\|[ \t]*$/gm, (_match, row) => row.split('|').map((cell) => cell.trim()).filter((cell) => cell !== '').join(' · '));
629
- // Collapse the blank runs the removals leave behind.
630
- text = text.replace(/\n{3,}/g, '\n\n').trim();
631
- return text;
632
- }
633
-
634
- /** Escape the four characters Telegram's HTML parser treats as markup. */
635
- function escapeHtml(value) {
636
- return String(value ?? '')
637
- .replace(/&/g, '&amp;')
638
- .replace(/</g, '&lt;')
639
- .replace(/>/g, '&gt;');
640
- }
641
-
642
- /** Inline markdown inside one non-code segment -> Telegram HTML. */
643
- function inlineHtml(segment) {
644
- let text = escapeHtml(segment);
645
- // Inline code first: its body must not be touched by the emphasis rules.
646
- text = text.replace(/`([^`\n]+)`/g, '<code>$1</code>');
647
- text = text.replace(/\*\*\*([^*]+)\*\*\*/g, '<b><i>$1</i></b>');
648
- text = text.replace(/\*\*([^*\n]+)\*\*/g, '<b>$1</b>');
649
- text = text.replace(/(^|[\s(])\*([^*\n]+)\*(?=[\s).,!?:;]|$)/g, '$1<i>$2</i>');
650
- text = text.replace(/__([^_\n]+)__/g, '<b>$1</b>');
651
- text = text.replace(/(^|[\s(])_([^_\n]+)_(?=[\s).,!?:;]|$)/g, '$1<i>$2</i>');
652
- text = text.replace(/~~([^~\n]+)~~/g, '<s>$1</s>');
653
- // Headings become bold lines.
654
- text = text.replace(/^[ \t]{0,3}#{1,6}[ \t]+(.+)$/gm, '<b>$1</b>');
655
- // Links: [label](url) -> label (url), both already escaped.
656
- text = text.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '$1 ($2)');
657
- // Blockquote markers.
658
- text = text.replace(/^[ \t]{0,3}&gt;[ \t]?/gm, '');
659
- // Bullets.
660
- text = text.replace(/^[ \t]*[-*+][ \t]+/gm, '— ');
661
- // Tables: drop the separator row, then join cells with a middle dot.
662
- text = text.replace(/^[ \t]*\|?[ \t:|-]*-[ \t:|-]*\|?[ \t]*$/gm, '');
663
- text = text.replace(/^[ \t]*\|(.+)\|[ \t]*$/gm, (_m, row) => row.split('|').map((cell) => cell.trim()).filter(Boolean).join(' · '));
664
- return text;
665
- }
666
-
667
- /**
668
- * Markdown -> Telegram HTML with real <pre><code> blocks.
669
- *
670
- * A fenced block is what gives the person a tap-to-copy button in Telegram,
671
- * which is the whole point for shell commands. Everything else stays plain so
672
- * a malformed entity cannot reject the message: `send` falls back to stripped
673
- * text when Telegram refuses to parse.
674
- */
675
- export function toTelegramHtml(input) {
676
- const source = String(input ?? '');
677
- const parts = source.split(/```/);
678
- let out = '';
679
- parts.forEach((segment, index) => {
680
- if (index % 2 === 1) {
681
- // Odd indexes are fenced code. The first line may be a language tag.
682
- const newline = segment.indexOf('\n');
683
- const firstLine = newline === -1 ? '' : segment.slice(0, newline).trim();
684
- const isLanguage = /^[a-zA-Z0-9+#.-]{1,20}$/.test(firstLine);
685
- const body = isLanguage ? segment.slice(newline + 1) : segment;
686
- const language = isLanguage ? firstLine.toLowerCase() : '';
687
- const cls = language ? ` class="language-${language}"` : '';
688
- out += `<pre><code${cls}>${escapeHtml(body.replace(/\n+$/, ''))}</code></pre>`;
689
- } else {
690
- out += inlineHtml(segment);
691
- }
692
- });
693
- return out.replace(/\n{3,}/g, '\n\n').trim();
694
- }
695
-
696
- /**
697
- * Language of a (chat, topic) pair, for the few helpers that have no message to
698
- * read it from: `send` falls back to this for its empty-text placeholder, and
699
- * the callback handler uses it for button answers.
700
- */
701
- function langFor(chatId, threadId = 0) {
702
- return resolveLang(state, sessionKey(chatId, threadId), null, config);
703
- }
704
-
705
577
  async function send(chatId, text, threadId = 0, replyTo = 0) {
706
578
  // Who is reading: the topic's language decides even the fallback line, so an
707
579
  // English or Chinese topic never sees a Russian placeholder.
708
580
  const lang = langFor(chatId, threadId);
709
- const html = config.plainText === true ? '' : toTelegramHtml(text);
710
- const parts = html ? chunk(html, 3800) : chunk(toPlainText(text) || t(lang, 'bridge.progress.empty'));
581
+ const plain = config.plainText === true;
582
+ const parts = plain
583
+ ? chunk(toPlainText(text) || t(lang, 'bridge.progress.empty'), 3800)
584
+ : markdownParts(text);
711
585
  let lastId = 0;
712
586
  for (const part of parts) {
713
- const body = { chat_id: chatId, text: part, disable_web_page_preview: true };
587
+ const html = plain ? '' : toTelegramHtml(part);
588
+ const body = { chat_id: chatId, text: html || part, disable_web_page_preview: true };
714
589
  if (html) body.parse_mode = 'HTML';
715
590
  // Without message_thread_id every reply lands in the General topic, which is
716
591
  // the whole point of carrying the thread through.
@@ -720,15 +595,18 @@ async function send(chatId, text, threadId = 0, replyTo = 0) {
720
595
  try {
721
596
  res = await tg('sendMessage', body);
722
597
  } catch (error) {
723
- // Bad HTML (a stray < or an unsupported tag) must not swallow the reply:
724
- // resend the same part as plain text.
598
+ // The fallback must start from the markdown, not from the HTML: resending
599
+ // the markup as plain text is exactly how the person ends up reading
600
+ // `<b>` and `<code>` instead of a sentence.
725
601
  if (!html) throw error;
726
602
  log(`html send failed (${String(error.message).slice(0, 120)}); resending as plain text`);
727
603
  delete body.parse_mode;
728
- body.text = toPlainText(part) || t(lang, 'bridge.progress.empty');
729
- res = await tg('sendMessage', body);
604
+ for (const piece of chunk(toPlainText(part) || t(lang, 'bridge.progress.empty'), 3800)) {
605
+ body.text = piece;
606
+ res = await tg('sendMessage', body);
607
+ }
730
608
  }
731
- log(`sent chat=${chatId}${threadId ? ` topic=${threadId}` : ''} msg=${res.message_id} len=${part.length}${html ? ' html' : ''}`);
609
+ log(`sent chat=${chatId}${threadId ? ` topic=${threadId}` : ''} msg=${res.message_id} len=${body.text.length}${html ? ' html' : ''}`);
732
610
  lastId = res.message_id;
733
611
  }
734
612
  return lastId;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tg-bridge",
3
- "version": "1.10.0",
3
+ "version": "1.10.1",
4
4
  "description": "Telegram bridge for DeepSeek Harness: text, voice, photos and project-per-topic sessions without opening the desktop app",
5
5
  "type": "module",
6
6
  "main": "plugin-bridge.mjs",